Imports, continued

August 6, 2014

I sent yesterday’s post about imports to Danny Gratzer. He had a follow-up question:

“Is there a Python equivalent to the Haskell trick of doing the following which will then export all 3 modules?”

module Foo (module X) where
import Data.Text as X
import Data.ByteString as X
import Control.Lens as X

The following should accomplish the same result, though it isn’t as concise due to Python’s lack of an embedded module language. Though Haskell’s module language is minimal1, it has one. In Python, file structure determines modules (and packages).

# foo/
from data.text import *
from data.byte_string import *
from control.lens import *

# foo/
import foo.x as x

from foo import x

I wouldn’t recommend these sorts of tricks as the import order affects what is in scope, e.g. if Data.Text and Data.ByteString both defined baz, which would be X.baz? Ideally import order should not matter as it is an implementation detail that should be hidden by a module. A language (or linter) can enforce that property by preventing imports with conflicting names in general.

  1. … relative to languages such as ML. There is ongoing work to improve Haskell’s module language.