Sub topic 8
Submodules and dotted names
This chapter assumes you can write import and from ... import statements, know that a package is a directory with an __init__.py file, and know that sys.modules caches loaded modules. Here you will see what a dotted name such as shapes.util.mathx means, what Python does when you import one, and which names end up bound in your namespace.
A dotted name is a path through packages
A submodule is a module that lives inside a package. Its full name joins the package names and the module name with dots. The running example is this layout:
shapes/
__init__.py
circle.py
util/
__init__.py
mathx.pyThe module in circle.py has the full name shapes.circle. The module in mathx.py has the full name shapes.util.mathx. In that name, shapes and shapes.util are packages and mathx is a plain module. Only packages can contain submodules. If util were a file util.py, then import shapes.util.mathx would fail with ModuleNotFoundError: No module named 'shapes.util.mathx'; 'shapes.util' is not a package.
Every module object records its full name in __name__. A package also has a __path__ list, which is where Python looks for that package's submodules. A plain module has no __path__. Its __package__ attribute names the package it belongs to, and Python uses it to resolve relative imports.
What `import a.b.c` does
Python imports each part of the dotted name in order, from left to right. For import shapes.util.mathx it does this:
- Import
shapes, unless"shapes"is already insys.modules. Runningshapes/__init__.pyfills the module object. - Import
shapes.util, searching the directories inshapes.__path__. Python runsshapes/util/__init__.py. - Import
shapes.util.mathx, searchingshapes.util.__path__, and runmathx.py. - Store each module in
sys.modulesunder its full dotted name. - Set each submodule as an attribute on its parent. After step 3,
shapes.util.mathxexists as an attribute of theshapes.utilmodule object.
A parent package is always imported before its child. This means __init__.py code always runs before any submodule code, even if you only asked for the submodule.
Which names get bound
The import statement always loads the whole chain. The forms differ in what they bind in your own namespace.
| Statement | Name bound | How you use it |
|---|---|---|
| `import shapes.util.mathx` | `shapes` (the top-level package) | `shapes.util.mathx.square(3)` |
| `import shapes.util.mathx as m` | `m` (the last module in the chain) | `m.square(3)` |
| `from shapes.util import mathx` | `mathx` | `mathx.square(3)` |
| `from shapes.util.mathx import square` | `square` | `square(3)` |
The first row surprises many people. import a.b.c binds a, not c. The deeper modules are reachable only as attributes, so each link in the chain must be a real attribute. The as form is the exception. It binds the alias directly to the final module, which is why import os.path as osp gives you osp and not os.
You cannot import an attribute with a plain import. import shapes.util.mathx.square fails because square is a function, not a module. Use from shapes.util.mathx import square for that.
Submodules are not imported automatically
Importing a package does not import its submodules unless something runs that import. Try this with the shapes layout above, assuming for this example that shapes/__init__.py is empty. Run it from the directory that contains shapes.
import sys
import shapes
print("shapes.circle" in sys.modules)
try:
shapes.circle
except AttributeError as exc:
print("AttributeError:", exc)
import shapes.util.mathx
print(sorted(name for name in sys.modules if name.startswith("shapes")))
print(shapes.util.mathx.square(3))
from shapes import circle
print(circle.area(2))The program prints:
False
AttributeError: module 'shapes' has no attribute 'circle'
['shapes', 'shapes.util', 'shapes.util.mathx']
9
12.56636import shapes only ran the empty __init__.py, so circle did not exist yet. The line from shapes import circle works because from first looks for an attribute named circle on shapes. When it finds none, it tries to import shapes.circle as a submodule. This fallback is specific to from package import name. Plain attribute access never triggers an import.
A related effect is that an import anywhere in the process changes what shapes looks like to everyone. Once any module runs import shapes.circle, the attribute shapes.circle exists for all code that holds a reference to shapes. Code that relies on this works by accident, and it breaks when the import in the other module is removed. Import every submodule you use, in the module that uses it.
Making submodules available from the package
The package author decides how much a bare import shapes provides. If shapes/__init__.py contains this line, as in the earlier example:
from .circle import area as circle_areathen importing shapes also imports shapes.circle, because the statement loads that submodule. That in turn runs from .util.mathx import square in circle.py, which loads shapes.util and shapes.util.mathx. After that, shapes.circle and shapes.util.mathx exist as attributes with no further imports.
This is convenient but has a cost. Every import shapes pays for loading every submodule it re-exports, including their dependencies. Large packages such as os and xml often leave submodules unloaded for this reason. os imports os.path for you, but import xml alone does not give you xml.dom.
Same name, different modules
The full dotted name is the identity of a module in sys.modules. Two files can share the leaf name without conflict, because shapes.util.mathx and other.util.mathx are different keys. Conflicts only happen when the same file is reachable under two different names. For example, a script run from inside shapes/ can import util.mathx as a top-level name. Python then loads the file a second time as util.mathx, and the two copies do not share state. Keep one canonical dotted name for each file, and import it by that name everywhere.
Common errors
ModuleNotFoundError: No module named 'shapes.util'; 'shapes' is not a package. Something namedshapeswas found, but it is a plain module, often your ownshapes.py. Rename it.AttributeError: module 'shapes' has no attribute 'circle'. You used the submodule without importing it. Addimport shapes.circleorfrom shapes import circle.ImportError: cannot import name 'x' from 'shapes.util'. The name is neither an attribute of the package nor a submodule on its__path__. Check spelling and whether__init__.pydefines it.- A relative import fails with
attempted relative import with no known parent package. The file was run as a script, so its__package__is empty. Run it withpython -minstead, which a later chapter covers.
Exercise
With the layout shown in this chapter and an empty shapes/__init__.py, you run import shapes.util.mathx as m. Which names exist in your namespace, which keys does sys.modules gain, and does shapes.circle exist?
Show answer
Only m is bound in your namespace. It refers to the shapes.util.mathx module, and the name shapes is not bound. sys.modules gains shapes, shapes.util, and shapes.util.mathx, because the whole chain is loaded. shapes.circle is not imported, because nothing asked for it and the empty __init__.py does not import it, so it is absent from sys.modules and is not an attribute of the package.