Skip to content
BIASED

Modules, packages and environments

Block 1 of 8~3 min

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.

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