Skip to content
BIASED

Modules, packages and environments

What import does step by step — the sys.modules cache, finders and sys.path — packages and relative imports, the __name__ == "__main__" guard, then virtual environments, pip and uv, pyproject.toml and lockfiles for reproducible experiments.

A file becomes a module

The topic Closures and decorators ended with a registry of models. A decorator records each class in a dict, and the dict fills up when the module that defines the classes is imported. A model whose module was never imported is simply missing. So far every program in this course has fit in one file. Real ML projects are split over many files, and most of their code was written by other people: NumPy, pandas, PyTorch. This topic follows import from the line you write to the file it runs, groups files into packages, and then pins down which versions of other people's code a project runs with.

A module is a file of Python code. Take a file metrics.py:

print("running metrics.py as", __name__)
EPS = 1e-12
 
def mean(xs):
    return sum(xs) / len(xs)

and a file train.py in the same folder:

import sys
import metrics
import metrics
 
losses = [0.9, 0.6, 0.45, 0.25]
print(metrics.mean(losses))
print("metrics" in sys.modules, sys.modules["metrics"] is metrics)
print(type(metrics).__name__, [k for k in vars(metrics) if not k.startswith("__")])
$ python train.py
running metrics.py as metrics
0.55
True True
module ['EPS', 'mean']

The module was imported twice but ran once. Importing gives an object of type module, and the global names of the file become its attributes: metrics.mean, metrics.EPS.

The forms of the statement differ only in which name they bind in the importing file:

  • import metrics binds metrics, the module. Every use shows where a name comes from.
  • import numpy as np binds the same kind of module object under a shorter alias.
  • from metrics import mean binds mean, the function. The whole module still runs.
  • from metrics import * binds every public name and hides where they came from. Leave it to the REPL.

from metrics import mean is an assignment in disguise, as in the topic Values, types and names. The importing file gets its own name for the same function object, and nothing links that name to the module afterwards.

What import does

What does import metrics actually do? Five steps, and most imports stop after the first.

  1. The cache. sys.modules is a dict from module names to module objects. If "metrics" is already there, the statement just binds the name. No file is read. That is why the second import metrics printed nothing, and why importing NumPy in ten files costs one load.
  2. The finders. Otherwise Python asks each object in sys.meta_path for a spec: where the module is and how to load it.
  3. The search. The last finder, PathFinder, walks the folders of sys.path in order. In each one it looks for a package folder metrics/, a file metrics.py or a compiled extension. The first match ends the search.
  4. Loading. The loader creates an empty module object, stores it in sys.modules first, and then runs the file's code with the module's dict as its global namespace. For a source file it reuses the bytecode cached in __pycache__ if the source has not changed, as in the topic Running Python.
  5. Binding. The statement binds metrics (or the alias, or the imported names) in the module that ran it.

A plain CPython 3.14 has three finders. Here they are, with the origin of three specs:

import importlib.util
import sys
 
print([f.__name__ for f in sys.meta_path])
for name in ("sys", "json", "metrics"):
    origin = importlib.util.find_spec(name).origin
    print(name, "->", "/".join(origin.split("/")[-2:]))
['BuiltinImporter', 'FrozenImporter', 'PathFinder']
sys -> built-in
json -> json/__init__.py
metrics -> expt/metrics.py

BuiltinImporter handles modules compiled into the interpreter, such as sys. FrozenImporter handles modules stored inside the interpreter's binary, such as parts of the import system itself. PathFinder finds everything else, including your files. Tools may add finders in front: an environment created by uv shows a fourth one, _Finder.

If every finder declines, you get ModuleNotFoundError: No module named 'numpy'. It almost always means "not installed for the interpreter you ran", not "not installed anywhere".

sys.path and shadowing

The order of sys.path decides which file wins. A script that prints it:

import sys
 
for entry in sys.path:
    print(entry)
.../expt
<base>/lib/python314.zip
<base>/lib/python3.14
<base>/lib/python3.14/lib-dynload
<base>/lib/python3.14/site-packages

Here <base> stands for the folder of the Python installation and ... for the start of a long path. In order:

  1. The folder of the script being run. For python -m, python -c and the REPL, the current folder.
  2. The folders listed in the environment variable PYTHONPATH, if it is set.
  3. The standard library: a zip file (usually absent), lib/python3.14, and lib-dynload for its compiled modules.
  4. site-packages, where installed third-party packages live.

The classic mistake: shadowing. The script's own folder comes first, so a file there with the name of a library replaces the library. Someone creates random.py to try things out, and later writes seed.py next to it:

import random
 
random.seed(0)
print(random.random())
$ python seed.py
my own random.py
Traceback (most recent call last):
  File ".../shadow/seed.py", line 3, in <module>
    random.seed(0)
    ^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'seed' (consider renaming '.../shadow/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

Since Python 3.13 the message names the culprit. Older versions only report the missing attribute. The usual victims are files called random.py, math.py, numpy.py, torch.py and test.py. Recognize it by an AttributeError on a function the library certainly has, and by random.__file__ pointing into your own folder.

The flag -P (Python 3.11 and later) leaves the script's folder out of sys.path, and -I (isolated mode) does that and more:

$ python -P seed.py
0.8444218515250481

The __name__ == "__main__" guard

Every module has a global __name__. When the file is imported, it holds the module's name. When the file is run as the program, with python metrics.py or python -m metrics, it holds "__main__". Add a self-test to the end of metrics.py:

if __name__ == "__main__":
    print("self-test:", mean([1, 2, 3]))
$ python metrics.py
running metrics.py as __main__
self-test: 2.0

python train.py prints exactly what it printed before: the module is imported, so the self-test is skipped. The guard lets one file be both a library and a small program.

In ML code the guard is not optional. multiprocessing, and PyTorch's DataLoader with num_workers > 0, start worker processes. With the start method spawn (the default on macOS and Windows) or forkserver (the default on Linux since Python 3.14), each worker is a fresh interpreter that imports the main file again, under the name __mp_main__:

import multiprocessing as mp
 
print("top level:", __name__, mp.current_process().name)
 
def work():
    print("worker is working")
 
if __name__ == "__main__":
    p = mp.Process(target=work)
    p.start()
    p.join()
$ python workers.py
top level: __main__ MainProcess
top level: __mp_main__ Process-1
worker is working

The top level ran in both processes, and the guarded part only in the main one. Without the guard, the worker would reach p.start() again while importing. Python stops that with a RuntimeError about starting a process "before the current process has finished its bootstrapping phase". A training loop at the top level of a script would at best run once more in every worker. Put the work in a main() function and call it under the guard. The topic Concurrency: threads, processes and asyncio returns to processes.

Packages

A package is a folder of modules that can itself be imported. A regular package contains a file __init__.py. Here is the registry from Closures and decorators, now spread over a package:

expt/
    pick.py
    zoo/
        __init__.py
        registry.py
        linear.py
        mlp.py
# zoo/registry.py
MODELS = {}
 
def register(name):
    def deco(cls):
        MODELS[name] = cls
        return cls
    return deco
 
# zoo/linear.py (mlp.py is the same with "mlp" and class MLP)
from .registry import register
 
@register("linear")
class Linear:
    pass
 
# zoo/__init__.py
print("initializing package", __name__)
from .registry import MODELS
from . import linear, mlp
# pick.py
import sys
import zoo
 
print(sorted(zoo.MODELS))
print(sorted(m for m in sys.modules if m.startswith("zoo")))
$ python pick.py
initializing package zoo
['linear', 'mlp']
['zoo', 'zoo.linear', 'zoo.mlp', 'zoo.registry']

Three rules explain this output.

  • Importing a package runs its __init__.py. The package is a module object, and its namespace is whatever __init__.py defined. Here __init__.py re-exports MODELS and imports every model module, so that import zoo fills the registry. Libraries such as timm do exactly this, and numpy and torch use their __init__.py to present a short public interface.
  • Submodules are found through the package. A package has __path__, a list of folders. import zoo.linear imports zoo first, then searches zoo.__path__ for linear. Each level lands in sys.modules under its dotted name.
  • A folder without __init__.py is a namespace package (PEP 420). It can be imported, has no initialization code, and may be spread over several folders. It exists for large distributions installed in parts. For your own code, write __init__.py, even an empty one.

Relative and circular imports

Inside a package there are two ways to name a neighbour. from zoo.registry import register is an absolute import. from .registry import register is a relative import: one dot means "the package this module belongs to", two dots its parent, and so on. Relative imports are resolved against the module's __package__, so they work only in a module imported as part of a package.

Take one more file, zoo/report.py:

from .registry import MODELS
 
print("report sees", sorted(MODELS))
$ python zoo/report.py
Traceback (most recent call last):
  File ".../expt/zoo/report.py", line 1, in <module>
    from .registry import MODELS
ImportError: attempted relative import with no known parent package
$ python -m zoo.report
initializing package zoo
report sees ['linear', 'mlp']

Run as a file, report.py is the module __main__, which belongs to no package. Run with -m and its dotted name from the folder that contains zoo/, it is the module zoo.report, and . means zoo. This is the main practical difference between python file.py and python -m name.

The other classic mistake: circular imports. In a package loop/, train.py starts with from .evaluate import score, and evaluate.py starts with from .train import fit:

$ python -c "import loop.train"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import loop.train
  File ".../expt/loop/train.py", line 1, in <module>
    from .evaluate import score
  File ".../expt/loop/evaluate.py", line 1, in <module>
    from .train import fit
ImportError: cannot import name 'fit' from partially initialized module 'loop.train' (most likely due to a circular import) (.../expt/loop/train.py)

Step 4 of the import put loop.train into sys.modules before its code ran. So evaluate finds the module, but train is still on its first line and has not defined fit yet. The fixes change the structure, not the syntax. Either move what both modules need into a third module that imports neither, or import the module instead of the name and look the name up when it is called.

Virtual environments and pip

pip install numpy copies NumPy into one site-packages folder, and every program run by that interpreter sees that one copy. Two projects that need different versions cannot both be satisfied, and an upgrade for one can break the other. The interpreter that came with the operating system belongs to the system: many Linux distributions and Homebrew mark it as externally managed (PEP 668), and pip refuses to install into it.

A virtual environment is a folder with its own site-packages and a small configuration file that points to a base interpreter. It reuses the base interpreter's standard library and copies nothing else (~ is the home folder):

$ python3.14 -m venv .venv
$ ls .venv
bin  include  lib  pyvenv.cfg
$ head -3 .venv/pyvenv.cfg
home = ~/.local/bin
include-system-site-packages = false
version = 3.14.7
$ .venv/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)"
True

When python starts, it looks for pyvenv.cfg next to its executable or one folder up. If it finds one, sys.prefix becomes the environment's folder, and the site-packages on sys.path becomes .venv/lib/python3.14/site-packages. sys.base_prefix still points to the base installation, whose standard library is used. On macOS and Linux, bin/python is only a symbolic link to the base interpreter.

Activation is a convenience. source .venv/bin/activate puts .venv/bin first on the shell's PATH, so that python and pip mean the environment's, and changes the prompt. Calling .venv/bin/python directly does the same without activation. An environment is disposable: rebuild it from a list of requirements, never copy it to another machine, never commit it to git.

pip ships with Python and installs packages from the Python Package Index (PyPI) into the environment of the interpreter that runs it. So the safe form names the interpreter:

$ .venv/bin/python -m pip install -q "numpy>=2.3,<3"
$ .venv/bin/python -m pip freeze
numpy==2.5.4

Packages arrive as wheels: zip files unpacked into site-packages as they are. A wheel with compiled code is built per Python version and platform. On this machine pip picked numpy-2.5.4-cp314-cp314-macosx_14_0_arm64.whl: NumPy 2.5.4 for CPython 3.14 on macOS 14 or later, on arm64. pip freeze lists what is installed, one name==version per line.

uv, pyproject.toml and lockfiles

uv is a package and project manager from Astral, written in Rust. One tool does the jobs of pip, venv and a Python installer, with a global cache that makes installs fast. A project from scratch, with uv 0.12.9 and its progress messages left out:

$ uv init --bare --python 3.14 lab
$ cd lab
$ uv add "numpy>=2.3"
$ uv add --dev pytest
$ uv run python -c "import numpy; print(numpy.__version__)"
2.5.4

uv add records the dependency, resolves versions, writes a lockfile and installs into lab/.venv. uv run syncs the environment, then runs the command inside it. The project now describes itself in pyproject.toml. Its [project] table is standardized (PEP 621), so every modern tool reads it:

[project]
name = "lab"
version = "0.1.0"
requires-python = ">=3.14"
dependencies = [
    "numpy>=2.3",
]
 
[dependency-groups]
dev = [
    "pytest>=9.2.0",
]

dependencies are what the code needs to run, given as ranges (PEP 440): ==2.5.4 exactly, >=2.3,<3 a range, ~=2.5.0 any 2.5.x from 2.5.0 on. [dependency-groups] (PEP 735) holds what developers need and users do not, such as the test runner.

Ranges are right for a library and wrong for an experiment. numpy>=2.3 resolved in March and in October gives different versions, and a result that depends on a changed default or a fixed bug cannot be repeated. A lockfile records the outcome of one resolution: the exact version of every package, direct and indirect, where it came from, and a hash of every file. Here uv.lock has 8 entries for 2 requested packages: the project itself, NumPy, pytest and its five dependencies, one of which (colorama) is marked as needed only on Windows. One entry, shortened:

[[package]]
name = "numpy"
version = "2.5.4"
source = { registry = "https://pypi.org/simple" }
wheels = [
    { url = "https://files.pythonhosted.org/.../numpy-2.5.4-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:956555e0…", size = 5455617 },
    ...
]

uv sync makes .venv match the lockfile exactly and checks every download against its hash. PEP 751 defines a standard lockfile, pylock.toml, and uv export --format pylock.toml writes one. The older equivalent is a fully pinned requirements.txt from pip freeze, without hashes.

For a reproducible ML experiment: commit pyproject.toml and the lockfile with the code, pin the interpreter (uv python pin 3.14 writes a .python-version file), and record the versions with every run. importlib.metadata.version("numpy") returns the installed one. Even then, some GPU kernels are nondeterministic, so results agree up to a tolerance, not bit for bit. The course MLOps: Machine Learning in Production builds on this: data versions, experiment tracking, containers.

The project now writes down what it needs from the outside world. The functions inside it still do not say what they need from each other: does mean take a list of floats, can a function return None? The next topic, Type hints, writes that into the code as well.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.