Course contents 13 / 22

13 / 22 · Abstraction

Modules, packages and environments

What import does, step by step: the sys.modules cache, finders and sys.path, packages with __init__.py and relative imports, and __name__ == '__main__'; then virtual environments, pip and uv, pyproject.toml, and lockfiles that make an ML experiment reproducible.

On this page 10

The previous note ended with a registry that is filled when a module is imported, and with the observation that a model whose module was never imported is missing from it. Until now every program in the course has been one file using the standard library. Real programs are split into many files, and most of their code comes from other people: NumPy, pandas, PyTorch. This note follows the import statement from the line you write to the file it finds and runs, shows how files are grouped into packages, and then turns to the question every ML project meets on its first day: which versions of which libraries does this code run with, and how does someone else get exactly the same ones.

Conventions. Paths are shown for macOS and Linux (.venv/bin/python); on Windows the interpreter of an environment is .venv\Scripts\python.exe. Tool versions are those installed on 22 October 2026: CPython 3.14.7, pip 26.2.1, uv 0.12.9.

Baseline: one long file#

A first project grows in one file: loading data, cleaning it, a model, training, plotting. At a few hundred lines it becomes hard to find anything, and the second project starts by copying the helper functions of the first. A fix made in one copy never reaches the other. Splitting the code into files that import each other solves both problems, if we understand what import does.

Modules#

A module is a file of Python code, and importing it gives an object of type module whose attributes are the names the file defined. Take a file helpers.py:

print("executing helpers.py, __name__ =", __name__)
RATE = 0.2

def tax(x):
    return x * RATE

if __name__ == "__main__":
    print("run as a script:", tax(100))

and a file main.py next to it:

import sys
import helpers
import helpers

print(helpers.tax(50), "helpers" in sys.modules, sys.modules["helpers"] is helpers)
print(type(helpers).__name__, sorted(k for k in vars(helpers) if not k.startswith("__")))
$ python main.py
executing helpers.py, __name__ = helpers
10.0 True True
module ['RATE', 'tax']

The module was imported twice and executed once. Its global names, RATE and tax, became attributes of the module object, reached as helpers.tax. The forms of the statement differ only in which name they bind in the importing file:

StatementBindsNotes
import helpershelpers, the modulethe usual form; the source of every name stays visible
import numpy as npnp, the modulean alias, conventional for a few libraries
from helpers import taxtax, the functionstill imports and runs the whole module
from helpers import *every public namehides where names come from; avoid outside the REPL

from helpers import tax copies a reference: if helpers later rebinds its own tax, the importing file still has the old function. That is the name model of the values note again, applied to modules.

What import does#

  1. The cache. sys.modules is a dictionary from module names to module objects. If the name is there, the statement only binds the name; no file is read. This is why the second import helpers printed nothing, and why importing a large library in ten files costs one load.
  2. The finders. Otherwise Python asks each object on sys.meta_path for a spec, a description of where the module is and how to load it. A plain CPython 3.14 has three: BuiltinImporter for modules compiled into the interpreter, such as sys; FrozenImporter for modules stored inside the interpreter binary, such as parts of the import machinery itself; and PathFinder. Tools may add finders of their own in front.
  3. sys.path. PathFinder takes each folder of sys.path in order and looks there for a package folder numpy/, a file numpy.py, or a compiled extension such as numpy.cpython-314-darwin.so. The first match ends the search.
  4. Loading. The loader creates an empty module object, puts it in sys.modules, and executes the module’s code with the module’s dictionary as its global namespace. For a source file, it uses the cached bytecode in __pycache__ when the source has not changed, as the first note described. The module goes into sys.modules before its code runs, which matters for circular imports, below.
  5. Binding. Finally the statement binds numpy (or the alias, or the imported names) in the namespace of the module that executed it.

If every finder declines, the statement raises ModuleNotFoundError: No module named 'numpy', which almost always means “not installed in the environment this interpreter uses”, not “not installed at all”.

What is on sys.path. In order:

  1. The folder of the script being run (python train.py), or the current folder for python -m, python -c and the REPL.
  2. The folders in the environment variable PYTHONPATH, if set.
  3. The standard library: a zip file (python314.zip, usually absent), the library folder lib/python3.14, and lib-dynload for its compiled extension modules.
  4. site-packages, where installed third-party packages live: the environment’s own, as the next sections explain.

The flag -I (isolated mode, which the Code sections of this course use) and the narrower -P (Python 3.11) leave out the first entry, so a stray file in the current folder cannot hijack an import. A script run with -I therefore cannot import a module that sits next to it unless it puts that folder on sys.path itself, as the Code section does.

The common mistake: shadowing. Because the script’s own folder comes first, a file there with the name of a library replaces the library. A script game.py next to a file of your own named random.py:

$ python game.py
my random.py
Traceback (most recent call last):
  File ".../shadow/game.py", line 2, in <module>
    print(random.randint(1, 6))
          ^^^^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'randint' (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. The classic victims are files called random.py, math.py, numpy.py, torch.py or test.py, created to try out the library of the same name. Recognize it by an AttributeError on a function the library certainly has, and by module.__file__ pointing into your own folder.

if __name__ == "__main__"#

Every module has a global __name__. When the module is imported, it is the module’s name, "helpers". When the file is run as the main program, with python helpers.py or python -m helpers, it is "__main__":

$ python helpers.py
executing helpers.py, __name__ = __main__
run as a script: 20.0

So the block under if __name__ == "__main__": runs when the file is a program and is skipped when it is a library. The idiom lets one file be both, typically a module with a small command-line entry point or a demonstration. It is required in one common ML situation: multiprocessing, and PyTorch’s DataLoader with num_workers > 0, start worker processes, and with the spawn start method (the default on macOS and Windows) or forkserver (the default on Linux since Python 3.14) each worker imports the main module again; code at the top level of the script, such as the training loop, would run again in every worker (ACOS, calling the system). Put the work in a main() function and call it under the guard.

Packages#

A package is a folder of modules that is itself importable. A regular package contains a file __init__.py:

shop/
    __init__.py
    cart.py
    payments/
        __init__.py
        card.py
# shop/__init__.py
print("initializing package", __name__)
from .cart import Cart

# shop/cart.py
from .payments.card import charge

class Cart:
    def __init__(self):
        self.items = []
    def checkout(self):
        return charge(sum(self.items))

# shop/payments/card.py
def charge(amount):
    return f"charged {amount}"
>>> import sys
>>> import shop
initializing package shop
>>> cart = shop.Cart()
>>> cart.items += [3, 4]
>>> cart.checkout()
'charged 7'
>>> sorted(m for m in sys.modules if m.startswith("shop"))
['shop', 'shop.cart', 'shop.payments', 'shop.payments.card']

The rules:

  • Importing a package runs its __init__.py. The package is a module object whose namespace is what __init__.py defined. Here it imports Cart so that users can write shop.Cart instead of shop.cart.Cart; libraries use __init__.py this way to present a short public interface, as numpy and torch do.
  • Submodules are found through the package. A package has a __path__, a list of folders, and import shop.payments.card imports shop, then searches shop.__path__ for payments, then that package’s path for card. Each level lands in sys.modules under its dotted name.
  • A folder without __init__.py is a namespace package (PEP 420): importable, with no initialization code, and possibly spread over several folders. It is meant for large distributions split into separately installed parts; for your own code, write the __init__.py, even empty, and avoid surprises.

Absolute and relative imports. Inside a package, from shop.payments.card import charge (absolute) and from .payments.card import charge (relative) import the same thing. One dot means “the package this module belongs to”, two dots its parent package, and so on. Relative imports are resolved against the module’s __package__, which is why they work only in modules imported as part of a package. Running such a file directly fails:

$ python shop/payments/report.py
Traceback (most recent call last):
  File ".../shop/payments/report.py", line 1, in <module>
    from ..cart import Cart
ImportError: attempted relative import with no known parent package
$ python -m shop.payments.report
initializing package shop
report sees Cart

Run as a file, report.py is the module __main__ with no package. Run with -m and its dotted name from the folder that contains shop/, it is the module shop.payments.report, and .. means shop. This is the main practical difference between python file.py and python -m name, introduced in the first note.

The common mistake: circular imports. If pk/x.py begins with from . import y and pk/y.py begins with from .x import f, then importing pk.x starts running x, which imports y, which asks for f from x, a module that is in sys.modules (step 4 put it there) but has not yet reached the line that defines f:

ImportError: cannot import name 'f' from partially initialized module 'pk.x' (most likely due to a circular import) (.../pk/x.py)

The fixes are structural: move what both modules need into a third module that imports neither, or import the module rather than the name (from . import x, then x.f() at call time, when x has finished running).

Why environments exist#

pip install numpy copies NumPy into one site-packages folder, and every program run by that interpreter sees the same copy. Two projects that need different versions of a library cannot both be satisfied, an upgrade for one project can break another, and the interpreter that came with the operating system belongs to the operating system: since PEP 668, many Linux distributions and Homebrew mark it as externally managed, 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:

$ python3.14 -m venv .venv
$ ls .venv .venv/bin
.venv:
bin  include  lib  pyvenv.cfg

.venv/bin:
Activate.ps1  activate  activate.csh  activate.fish  python  python3  python3.14  𝜋thon
$ .venv/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)"
True

The rule that makes it work (venv documentation, How venvs work): when python starts, it looks for pyvenv.cfg next to the executable or one folder up. If it finds one, it sets sys.prefix to the environment’s folder, and site-packages on sys.path becomes .venv/lib/python3.14/site-packages, while sys.base_prefix keeps pointing to the base installation whose standard library is used. bin/python is only a symbolic link to the base interpreter. (𝜋thon is a joke alias that the 3.14 venv adds; it is the same link.)

Activation is a convenience, not a requirement. 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 has the same effect without activation. An environment is disposable: it is rebuilt from a list of requirements, never copied between machines and never committed to git.

Installing packages: pip and uv#

pip ships with Python and installs packages from the Python Package Index, PyPI, into the environment of the interpreter that runs it, which is why the safe form is python -m pip:

$ python -m pip install "numpy>=2.3,<3" pandas
$ python -m pip freeze > requirements.txt

Packages are distributed as wheels, zip files that are unpacked into site-packages as they are, built per Python version and platform when they contain compiled code (numpy-2.5.3-cp312-cp312-macosx_14_0_arm64.whl is NumPy 2.5.3 for CPython 3.12 on macOS 14 or later on arm64). pip resolves the dependencies of what you ask for, downloads compatible wheels and installs them; pip freeze lists what is installed, one name==version per line. The version specifiers are those of PEP 440: ==2.5.4 exactly, >=2.3,<3 a range, ~=2.5.0 any 2.5.x from 2.5.0.

uv is a package and project manager from Astral, written in Rust, first released in 2024 (uv documentation). It does what pip, venv, pip-tools and a Python installer do, with one command and a global cache that makes installs fast. A project workflow:

$ uv init --bare expt          # writes expt/pyproject.toml
$ cd expt
$ uv add "numpy>=2.3" pandas   # records the dependencies, resolves, locks, installs into .venv
$ uv add --dev pytest          # a development-only dependency
$ uv run python train.py       # runs inside the project's environment, syncing it first
$ uv sync                      # makes .venv match the lockfile exactly

Both tools are good choices in 2026. pip is always present and enough for a single environment; uv manages the whole project and its lockfile, and is what this site’s courses use. Conda remains common where non-Python libraries, such as particular CUDA versions, must come with the packages.

pyproject.toml#

A project describes itself in a file pyproject.toml at its root, in the TOML format. The table [project] is standardized by PEP 621, and every modern tool reads it:

[project]
name = "expt"
version = "0.1.0"
requires-python = ">=3.14"
dependencies = [
    "numpy>=2.3",
    "pandas>=3.0",
]

[dependency-groups]
dev = ["pytest>=9.0"]

dependencies lists what the code needs to run, as ranges: the project should work with any NumPy from 2.3 on. requires-python states the interpreter versions. [dependency-groups] (PEP 735) lists what developers need but users do not, such as the test runner. A project that is meant to be installed as a package also has a [build-system] table (PEP 518) that names the tool that builds its wheel.

Lockfiles and reproducible experiments#

Ranges in pyproject.toml 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, a fixed bug or a new random-number stream cannot be reproduced. 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 each file.

# uv.lock, one entry (hashes shortened)
[[package]]
name = "numpy"
version = "2.5.3"
source = { registry = "https://pypi.org/simple" }
wheels = [
    { url = "https://files.pythonhosted.org/.../numpy-2.5.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a72f87…", size = 5445405 },
    ...
]

uv lock writes uv.lock; uv sync installs exactly what it says, and checks each downloaded file against its hash. The standard format for lockfiles is pylock.toml, defined by PEP 751 (accepted in March 2025): uv export --format pylock.toml writes one, and pip 26.2.1 can produce one with pip lock, still marked experimental. The older equivalent is a requirements.txt with every version pinned, from pip freeze, which records versions but not hashes or the dependency graph.

For an ML experiment, reproducibility needs more than the lockfile, and each piece is cheap:

  1. Commit pyproject.toml and the lockfile with the code, and rebuild the environment from them (uv sync), never by hand.
  2. Fix the interpreter version. requires-python gives a range; a .python-version file (written by uv init) or the lockfile’s resolution pins what the project uses.
  3. Mind the platform. Wheels with compiled code differ by operating system, processor and, for PyTorch, CUDA version; a lockfile can cover several platforms, but a result from a GPU machine is reproduced on the same kind of machine.
  4. Record versions with results. importlib.metadata.version("numpy") returns the installed version; save it, the git commit and the random seeds in the log of every run.
  5. Know what a lockfile cannot fix. Some GPU kernels are nondeterministic, and floating-point sums depend on the order of operations; the same environment then gives results equal to a tolerance, not bit for bit. The Deep Learning course sets seeds for this reason.

What changed#

One long file (the baseline)Modules, packages and environments
Reusing codecopy and pasteimport from a module or package
How often shared code runsevery copy, separatelyonce per process, cached in sys.modules
Where Python looksthe script’s folder onlysys.path: script folder, standard library, the environment’s site-packages
Library versionswhatever is installed globallyper project, in a virtual environment
Declaring dependenciesin a README, if at allpyproject.toml, as ranges
Repeating an experimenthopea lockfile, the Python version and logged versions

Limitations#

  • The import system can be extended with custom finders and loaders, import hooks and importlib.resources for data files; the note shows the default path only.
  • Packaging a library for others, with build backends, wheels for several platforms and publishing to PyPI, is a subject of its own; the Python Packaging User Guide covers it.
  • Tool versions move quickly: the commands here are those of uv 0.12.9 and pip 26.2.1. The standards they implement (PEP 440, 621, 735, 751) change slowly.
  • Python 3.15, released in October 2026, adds explicit lazy imports, lazy import json, which defer loading a module until its first use (PEP 810, accepted in November 2025). The behaviour of ordinary import described here does not change.

What you should remember#

  • import checks sys.modules, asks the finders, searches sys.path in order, runs the module once and binds a name. The first match on sys.path wins, so never name a file after a library.
  • if __name__ == "__main__": separates a file’s program part from its library part; scripts that start worker processes need it.
  • A package is a folder with __init__.py; relative imports work inside packages, so run package modules with python -m.
  • A virtual environment is a folder with its own site-packages, found through pyvenv.cfg. One per project, rebuilt rather than copied.
  • pyproject.toml declares ranges; a lockfile records exact versions and hashes. For experiments, commit both and log the versions with the results.

Code#

The script builds a small project in a temporary folder and runs the import system on it: the cache, the spec of a module, a package with relative imports, the finders and the origins find_spec reports, __name__ in a module run as a program, a relative import run both ways, the shadowing of random, and a fresh virtual environment. It needs only the standard library and no network; run it with python -I modules.py. It takes under a second and deletes its folder at the end.

"""Modules, packages and environments: the import system at work, in a temporary folder (Python 3.14)."""
import importlib
import importlib.metadata
import importlib.util
import shutil
import subprocess
import sys
import tempfile
import venv
from pathlib import Path

root = Path(tempfile.mkdtemp())
files = {
    "helpers.py": 'print("running helpers.py as", __name__)\nRATE = 0.2\n'
                  'def tax(x):\n    return x * RATE\n'
                  'if __name__ == "__main__":\n    print("tax(100) =", tax(100))\n',
    "shop/__init__.py": 'print("initializing package", __name__)\nfrom .cart import Cart\n',
    "shop/cart.py": "from .payments.card import charge\n\nclass Cart:\n    def __init__(self):\n"
                    "        self.items = []\n    def checkout(self):\n        return charge(sum(self.items))\n",
    "shop/payments/__init__.py": "",
    "shop/payments/card.py": 'def charge(amount):\n    return f"charged {amount}"\n',
    "shop/payments/report.py": "from ..cart import Cart\nprint('report sees', Cart.__name__)\n",
    "shadow/random.py": 'print("my own random.py")\n',
    "shadow/game.py": "import random\nprint(random.randint(1, 6))\n",
}
for name, text in files.items():
    (root / name).parent.mkdir(parents=True, exist_ok=True)
    (root / name).write_text(text)

# 1. sys.path decides where imports look; -I leaves out the script's folder, so add ours
print("isolated:", bool(sys.flags.isolated), "| first entries:", [Path(p).name for p in sys.path[:2]])
sys.path.insert(0, str(root))

# 2. A module runs once; later imports return the object cached in sys.modules
import helpers
import helpers
print(helpers.tax(50), sys.modules["helpers"] is helpers, Path(helpers.__file__).name)
print("spec:", helpers.__spec__.name, "found by", type(helpers.__spec__.loader).__name__)
importlib.reload(helpers)                       # runs the file again, into the same module object

# 3. A package: importing it runs __init__.py; submodules use relative imports
import shop
cart = shop.Cart()
cart.items += [3, 4]
print(cart.checkout(), sorted(m for m in sys.modules if m.startswith("shop")))
print("package path:", Path(shop.__path__[0]).name, "| cart.__package__:", shop.cart.__package__)

# 4. The finders on sys.meta_path, and what find_spec reports for three kinds of module
print([f.__name__ if isinstance(f, type) else type(f).__name__ for f in sys.meta_path])  # tools may add their own
for name in ("sys", "json", "helpers"):
    spec = importlib.util.find_spec(name)
    origin = spec.origin if spec.origin in ("built-in", "frozen") else Path(spec.origin).name
    print(f"  {name:8s} origin={origin:12s} package={spec.submodule_search_locations is not None}")

# 5. __name__: "__main__" when run, the module's name when imported; -m runs a module found by name
def run(*args, cwd=root, python=sys.executable):
    out = subprocess.run([python, *args], cwd=cwd, capture_output=True, text=True)
    return (out.stdout + out.stderr).strip().splitlines()

print(run("helpers.py"))
print(run("shop/payments/report.py")[-1])      # a relative import in a file run as a script
print(run("-m", "shop.payments.report"))       # the same file, run as a module of its package
print(run("game.py", cwd=root / "shadow")[-1][:62] + " ...")

# 6. A virtual environment: its own site-packages, the same standard library
env = root / ".venv"
venv.create(env, with_pip=False)
print([line.split(" = ")[0] for line in (env / "pyvenv.cfg").read_text().splitlines()])
env_python = env / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
print(run("-I", "-c", "import sys; print(sys.prefix != sys.base_prefix, sys.path[-1].endswith('site-packages'))",
          python=env_python))

# 7. Which versions does this environment have? Record them with every experiment
for dist in ("numpy", "pandas"):
    try:
        print(dist, importlib.metadata.version(dist))
    except importlib.metadata.PackageNotFoundError:
        print(dist, "not installed in this environment")

shutil.rmtree(root)                            # remove the temporary folder

# Output with CPython 3.14.7 on macOS (arm64), run in an environment created by uv
# (which adds the finder _Finder; a plain interpreter lists only the other three):
# isolated: True | first entries: ['python314.zip', 'python3.14']
# running helpers.py as helpers
# 10.0 True helpers.py
# spec: helpers found by SourceFileLoader
# running helpers.py as helpers
# initializing package shop
# charged 7 ['shop', 'shop.cart', 'shop.payments', 'shop.payments.card']
# package path: shop | cart.__package__: shop
# ['_Finder', 'BuiltinImporter', 'FrozenImporter', 'PathFinder']
#   sys      origin=built-in     package=False
#   json     origin=__init__.py  package=True
#   helpers  origin=helpers.py   package=False
# ['running helpers.py as __main__', 'tax(100) = 20.0']
# ImportError: attempted relative import with no known parent package
# ['initializing package shop', 'report sees Cart']
# AttributeError: module 'random' has no attribute 'randint' (co ...
# ['home', 'include-system-site-packages', 'version', 'executable', 'command']
# ['True True']
# numpy 2.5.4
# pandas 3.0.6

The first line shows isolated mode at work: sys.path starts with the standard library, not with the script’s folder. importlib.reload printed the helpers line a second time; it is the only way to run a module’s code again in the same process, and it updates the existing module object rather than creating a new one. The last two lines depend on what the environment has installed.

Next#

The modules of this note can now be imported anywhere, and pyproject.toml says which versions of NumPy and pandas they need. What they still do not say is what their own functions accept and return: whether tax takes a float or a string, whether a function may return None. The next note adds that information as type hints, shows what Python 3.14 does with it at run time, which is almost nothing, and what a type checker does with it before the program runs.

References#