Modules

Packages

Packages organize modules into importable directories.

A package is itself a module. The json package exposes a namespace that can contain submodules.

Source

import json

print(json.__name__)

Output

json
MYPACKAGE__init__.pya.pyb.pysub/
A directory with __init__.py becomes an importable package; submodules and subpackages nest beneath it.

Dotted 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
JSONDecoder

importlib.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

True

Inside 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

See also

Run the complete example

Example code

Expected output

json
json.decoder
JSONDecoder
True
9
['area']

Execution time appears here after you run the example.