Modules
Packages
A package is itself a module. The json package exposes a namespace that can contain submodules.
Source
import json
print(json.__name__)Output
jsonDotted imports name a path through a package. Importing json.decoder makes that submodule available under the package namespace.
Source
import json.decoder
print(json.decoder.__name__)
print(json.decoder.JSONDecoder.__name__)Output
json.decoder
JSONDecoderimportlib.import_module() imports by string. It is useful for plugin systems and dynamic imports, but ordinary import is clearer when the dependency is known.
Source
import importlib
module = importlib.import_module("json.decoder")
print(module is json.decoder)Output
TrueInside a package's __init__.py, from .submodule import name re-exports a submodule's name at the package root, and __all__ lists the names that from package import * should make visible. This cell builds a temporary shapes package on disk to make both forms concrete.
Source
import os
import sys
import tempfile
with tempfile.TemporaryDirectory() as tmp:
pkg = os.path.join(tmp, "shapes")
os.makedirs(pkg)
with open(os.path.join(pkg, "__init__.py"), "w") as init:
init.write("from .square import area\n__all__ = ['area']\n")
with open(os.path.join(pkg, "square.py"), "w") as square:
square.write("def area(side):\n return side * side\n")
sys.path.insert(0, tmp)
try:
import shapes
print(shapes.area(3))
print(shapes.__all__)
finally:
sys.path.remove(tmp)
sys.modules.pop("shapes", None)
sys.modules.pop("shapes.square", None)Output
9
['area']Notes
- A package is a module that can contain submodules.
- Dotted imports should mirror a meaningful project structure.
- Use
from .submodule import nameinside a package to re-export submodule names; set__all__to declare the public surface. - Prefer ordinary imports unless the module name is truly dynamic.
See also
- related: Modules
- related: Import Aliases
- related: Virtual Environments
Run the complete example
Expected output
json
json.decoder
JSONDecoder
True
9
['area']
Execution time appears here after you run the example.