Skip to content

08. Modules, packages and environments — Cheat sheet

The essentials of module 08 on one page. Every runnable block on this page is checked against its output. Commands that need the network are shown, not run.

I want to… Use… Example
load a module import module import csv
load a module under a short name import module as alias import pandas as pd
load a few names from module import name from pathlib import Path
load a name from a submodule from package.module import name from salesreport.stats import revenue_by
import a neighbor inside a package relative import from .loader import load_sales
run code only when the file is run the main guard if __name__ == "__main__": main()
run a package or module by name python -m name python -m salesreport data/sales.csv
make a package runnable a __main__.py file raise SystemExit(main())
see where Python looks for modules sys.path print(sys.path)
see where a module came from module.__file__ print(pandas.__file__)
check the version of a package importlib.metadata.version() version("scikit-learn")
map import names to distributions packages_distributions() {"sklearn": ["scikit-learn"], ...}
check for a virtual environment sys.prefix != sys.base_prefix True inside .venv
read the command-line words sys.argv ['report.py', 'data/sales.csv']
build a command-line interface argparse.ArgumentParser parser.add_argument("--top", type=int)
test a parser without a terminal parser.parse_args([...]) parse_args(["data/sales.csv", "--top", "3"])
stop with a usage error (exit code 2) parser.error(message) parser.error("file not found")
end a program with an exit code raise SystemExit(code) or sys.exit(code) raise SystemExit(main())
read a TOML file tomllib.load(binary_file) tomllib.load(open("pyproject.toml", "rb"))
create an environment uv venv or python -m venv .venv
install a package uv pip install or python -m pip install uv pip install "pandas>=3.1,<4"
add a dependency to a project uv add uv add pandas
record exact versions uv lock, uv pip compile, pip freeze uv pip freeze > requirements.txt
rebuild the exact environment uv sync, uv pip sync uv pip sync requirements.txt
install your project for development editable install uv pip install -e .
Form Binds Note
import csv csv default; the source of each name stays visible
import numpy as np np use the community aliases: np, pd, pl, plt, sns
from pathlib import Path Path for names you use often
from os import path as osp osp rename one name
import xml.etree.ElementTree as ET ET a submodule under a short name
from csv import * every public name avoid; __all__ decides what * gives
import importlib; importlib.reload(m) — rerun a changed module in a REPL session
import json
import sys
from importlib.metadata import version
from pathlib import Path
import pandas as pd
print(sys.modules["json"] is json) # a module is loaded once, then cached
print(pd.__name__, version("pandas")) # the alias keeps the real name
print(Path(pd.__file__).parent.parent.name) # third-party code lives in site-packages
print("csv" in sys.stdlib_module_names) # is it a standard library name?
Output
True
pandas 3.1.1
site-packages
True

PEP 8 order: standard library, a blank line, third-party packages, a blank line, your own modules. ruff check --select I --fix sorts them.

Step What Python does
1 Look in sys.modules (the cache). Found: reuse it, done.
2 Search each folder of sys.path for name.py or a folder name/.
3 Create the module and run its code top to bottom (only the first time).
4 Store it in sys.modules and bind the name.
sys.path entry (in order) Holds
script folder (python file.py) or current folder (-m, -c, REPL) your modules; first, so it can shadow others
PYTHONPATH folders only if you set the variable
standard library folders csv, json, argparse, …
site-packages of the active environment third-party packages
Error Usual cause Fix
ModuleNotFoundError: No module named 'pandas' not installed in the active environment, or a typo check sys.prefix; install there
ModuleNotFoundError: No module named 'salesreport' run from the wrong folder cd to the folder that contains salesreport/
ImportError: attempted relative import with no known parent package a package file run by path python -m package
ImportError: cannot import name 'x' from partially initialized module circular import move shared code to a third module
AttributeError: module 'csv' has no attribute 'reader' your csv.py shadows the real module rename the file
How the file runs __name__
python report.py "__main__"
python -m salesreport (the package’s __main__.py) "__main__"
import report "report"
import salesreport.cli "salesreport.cli"
Script template
"""report.py: one line that says what the script does."""
import argparse
def build_parser():
parser = argparse.ArgumentParser(description="...")
parser.add_argument("path")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
... # the work
return 0 # the exit code
if __name__ == "__main__":
raise SystemExit(main())
Flat layout
project/
├── pyproject.toml
├── data/
├── salesreport/
│ ├── __init__.py # import salesreport; __version__, public names
│ ├── __main__.py # python -m salesreport
│ ├── cli.py # argparse
│ ├── loader.py
│ └── stats.py
└── tests/
└── test_stats.py
File or idea Purpose
__init__.py makes a regular package; runs on import package; holds __version__ and __all__
__main__.py runs on python -m package
__all__ = [...] the public names; what from package import * gives
submodule a module in a package: salesreport.stats
subpackage a package in a package: sklearn.linear_model
from .loader import x relative import: . this package, .. the parent
from salesreport.loader import x absolute import: the full dotted name
namespace package a folder without __init__.py; for large multi-folder projects
src layout package in src/; tests run against the installed package
Command Runs
python -m salesreport args salesreport/__main__.py
python -m salesreport.cli salesreport/cli.py as __main__ (needs its own main guard)
python -m venv .venv the standard library’s venv tool
python -m pip install x pip of this exact Python
python -m pytest -q pytest, with the current folder on sys.path
python -m json.tool data/config.json pretty-print a JSON file
python -m http.server 8000 serve the current folder on port 8000
python -m timeit "sum(range(1000))" time a statement (module 15)
pyproject.toml
[project]
name = "salesreport" # distribution name (pip install salesreport)
version = "0.1.0" # MAJOR.MINOR.PATCH
description = "Summarize the revenue in a sales CSV file."
requires-python = ">=3.12" # installers refuse older Pythons
license = "MIT" # SPDX identifier
authors = [{ name = "Ada Lovelace", email = "ada@example.com" }]
dependencies = ["pandas>=3.1,<4"] # run-time needs, as ranges
[project.optional-dependencies]
plots = ["matplotlib>=3.11"] # pip install "salesreport[plots]"
[project.scripts]
salesreport = "salesreport.cli:main" # command = "module:function"
[dependency-groups]
dev = ["pytest>=9.2", "ruff>=0.17"] # developer tools, never installed for users
[build-system]
requires = ["hatchling>=1.27"] # what the installer needs to build
build-backend = "hatchling.build"
[tool.ruff]
line-length = 88 # each tool reads its own [tool.NAME] table
Table Read by Holds
[project] installers, build tools, PyPI metadata and dependencies (PEP 621)
[project.optional-dependencies] installers extras: optional feature sets, pkg[extra]
[project.scripts] installers entry-point commands
[dependency-groups] uv, pip 25.1+ (--group) dev, test, docs tools (PEP 735)
[build-system] installers, uv build the build backend (PEP 517/518)
[tool.*] each tool ruff, mypy, pytest, uv settings
import tomllib
text = """
[project]
name = "salesreport"
version = "0.1.0"
dependencies = ["pandas>=3.1,<4"]
[project.scripts]
salesreport = "salesreport.cli:main"
"""
config = tomllib.loads(text) # tomllib.load(f) for a file opened with "rb"
print(config["project"]["dependencies"], config["project"]["scripts"])
Output
['pandas>=3.1,<4'] {'salesreport': 'salesreport.cli:main'}
add_argument(...) Effect Value when absent
"path" positional, required error
"path", nargs="?" positional, optional default
"files", nargs="+" one or more values, as a list error
"--top", type=int, default=5 option with a converted value 5
"-n", "--top" short and long form; attribute top
"--by", choices=["a", "b"] only these values None or default
"--share", action="store_true" flag False
"--no-header", action="store_false", dest="header" inverted flag True
"--sensor", action="append" repeatable; a list None
"-v", "--verbose", action="count", default=0 -vv gives 2 0
"--version", action="version", version="%(prog)s 1.0" prints and exits
"--key", required=True mandatory option error
help="... (default: %(default)s)" help text with the default
metavar="N" the placeholder in help: --top N
dest="name" the attribute name --min-revenue → min_revenue
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(prog="topsales", description="Rank sales groups.")
parser.add_argument("path", type=Path) # positional, converted to Path
parser.add_argument("--by", choices=["category", "region"], default="category")
parser.add_argument("-n", "--top", type=int, default=5, metavar="N")
parser.add_argument("--min-revenue", type=float, default=0.0) # -> args.min_revenue
parser.add_argument("--share", action="store_true") # flag
parser.add_argument("--sensor", action="append") # repeatable -> list
parser.add_argument("-v", "--verbose", action="count", default=0)
args = parser.parse_args(["data/sales.csv", "-n", "3", "--share", "-vv"])
print(args.path.name, args.by, args.top, args.min_revenue, args.share, args.verbose)
print(parser.parse_args(["x.csv", "--sensor", "S3", "--sensor", "S4"]).sensor)
print(parser.format_usage().strip())
Output
sales.csv category 3 0.0 True 2
['S3', 'S4']
usage: topsales [-h] [--by {category,region}] [-n N] [--min-revenue MIN_REVENUE] [--share]
[--sensor SENSOR] [-v]
path

format_usage() returns the usage lines that --help and every error message start with. argparse wraps them to the terminal width.

import argparse
def positive_int(text): # a custom type: str in, value out
value = int(text) # a ValueError becomes "invalid positive_int value"
if value < 1:
raise argparse.ArgumentTypeError(f"must be at least 1, got {value}")
return value
sub = argparse.ArgumentParser(prog="salescli")
commands = sub.add_subparsers(dest="command", required=True) # git-style subcommands
top = commands.add_parser("top")
top.add_argument("--top", type=positive_int, default=5)
summary = commands.add_parser("summary")
print(sub.parse_args(["top", "--top", "2"]), sub.parse_args(["summary"]))
Output
Namespace(command='top', top=2) Namespace(command='summary')
On bad input argparse…
prints the usage line and prog: error: argument --top: ... to stderr
exits with code 2 (SystemExit(2))
--help exits with code 0
Exit code Meaning
0 success
1 general failure (an uncaught exception also gives 1)
2 usage error (argparse)
read it bash/zsh: echo $?; PowerShell: $LASTEXITCODE
Part macOS / Linux Windows
interpreter and commands .venv/bin/python, .venv/bin/ruff .venv\Scripts\python.exe
packages .venv/lib/python3.13/site-packages/ .venv\Lib\site-packages\
config .venv/pyvenv.cfg (home, version, include-system-site-packages) same
activate source .venv/bin/activate .venv\Scripts\activate
leave deactivate deactivate
import sys
from pathlib import Path
print(Path(sys.prefix).name) # the environment that runs now
print(sys.prefix != sys.base_prefix) # True inside a virtual environment
print(sys.version_info >= (3, 12)) # compare versions as tuples, never as strings
Output
.venv
True
True
  • Activation only puts .venv/bin first in PATH. .venv/bin/python file.py and uv run work without it.
  • An environment cannot be moved or renamed. Delete it and rebuild it.
  • Never commit .venv. Add .venv/ to .gitignore.

These commands need the network or change your environment, so they are shown, not run.

Terminal
# --- environments ---
uv venv --python 3.13 # create .venv
python -m venv .venv # the same with the standard library
# --- uv project workflow (pyproject.toml + uv.lock) ---
uv init # new project; --package for a src layout
uv add "pandas>=3.1" # add a dependency, lock, install
uv add --dev pytest # add to [dependency-groups] dev
uv remove pandas # remove a dependency
uv lock # resolve and write uv.lock
uv lock --upgrade-package pandas # allow a newer pandas in the lock
uv sync # make .venv match uv.lock exactly
uv sync --locked # fail if uv.lock is out of date (CI)
uv run python -m salesreport data/sales.csv
uv tree # dependency tree
uv export --output-file requirements.txt # lock -> pinned requirements file
uv build # build a wheel and a source archive
# --- pip-style commands ---
uv pip install -r requirements.txt # or: python -m pip install -r ...
uv pip install -e . # editable install of this project
uv pip list # installed packages
uv pip show pandas # details and dependencies of one package
uv pip freeze > requirements.txt # exact versions of everything installed
uv pip compile pyproject.toml -o requirements.txt # pin all dependencies
uv pip sync requirements.txt # install exactly the list, remove the rest
uv pip uninstall pandas
requirements-dev.txt
# a comment; also allowed after a requirement
-r requirements.txt # include another requirements file
-c constraints.txt # cap versions; installs nothing itself
pytest==9.2.0 # requirement with a pin
tzdata==2026.6 ; sys_platform == "win32" # environment marker
-e . # editable install of this project
Task Command
install a list uv pip install -r requirements.txt / python -m pip install -r requirements.txt
pin every dependency of requirements.in uv pip compile requirements.in -o requirements.txt
also write file hashes uv pip compile requirements.in -o requirements.txt --generate-hashes
refuse any file without a matching hash python -m pip install --require-hashes -r requirements.txt
make the environment match the list exactly uv pip sync requirements.txt
dump what is installed uv pip freeze > requirements.txt

A compiled file pins every package and says which package needs it:

requirements.txt (excerpt, written by uv pip compile)
pandas==3.1.1
# via -r requirements.in
threadpoolctl==3.8.0
# via scikit-learn

With --generate-hashes, every pin also lists the SHA-256 hash of each allowed file:

requirements.txt (excerpt, with --generate-hashes)
threadpoolctl==3.8.0 \
--hash=sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137 \
--hash=sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da
# via scikit-learn
Specifier Allows
==3.1.1 exactly 3.1.1 (pin)
>=3.1 3.1 and newer
>=3.1,<4 3.1 up to, not including, 4.0
~=3.1 >=3.1, ==3.*
~=3.1.1 >=3.1.1, ==3.1.*
!=3.0.2 all but 3.0.2
==3.1.* any 3.1.x
; sys_platform == "win32" environment marker: only on Windows
; python_version < "3.14" only on older Pythons
pandas[excel] the package plus its excel extra
from packaging.specifiers import SpecifierSet # the library pip and uv rules follow
versions = ["1.9.0", "1.9.1", "1.10.0", "2.0.0"]
for spec in ["~=1.9", "~=1.9.0", ">=1.9,<2", "==1.9.*"]:
print(f"{spec:<9}", [v for v in versions if SpecifierSet(spec).contains(v)])
Output
~=1.9 ['1.9.0', '1.9.1', '1.10.0']
~=1.9.0 ['1.9.0', '1.9.1']
>=1.9,<2 ['1.9.0', '1.9.1', '1.10.0']
==1.9.* ['1.9.0', '1.9.1']
File Holds Who writes it Commit it?
pyproject.toml direct dependencies as ranges you or uv add yes
requirements.txt name==version lines you, pip freeze, uv pip compile, uv export yes, for applications
uv.lock every package, exact versions and hashes, all platforms uv yes
pylock.toml the same, in the PEP 751 standard format uv export, pip lock (experimental) yes
.venv/ the installed packages uv or venv no
Project kind dependencies Reproducibility
library others install ranges: pandas>=3.1,<4 tests in CI against the lock and the newest versions
application, analysis, model training ranges a lock file (uv.lock) or a fully pinned requirements.txt
  • A file named csv.py, random.py, statistics.py, email.py or pandas.py in your folder hides the real module. Rename it; Python 3.13+ names the file in the error hint. The __pycache__ folder needs no cleanup.
  • Top-level code in a module runs on every first import. Put work in main() under if __name__ == "__main__":.
  • "__main__" has two underscores on each side. if __name__ == "main": is never true.
  • A package file run by path (python pkg/cli.py) cannot use relative imports. Run python -m pkg.
  • python -m pkg must run from the folder that contains pkg/, or after an install.
  • A module is imported once per process. Editing it does not change a running REPL; use importlib.reload() or restart.
  • version() takes the distribution name (scikit-learn, PyYAML), not the import name (sklearn, yaml).
  • type=bool in argparse makes --flag False truthy. Use action="store_true".
  • argparse stores --min-revenue as args.min_revenue.
  • Without type=, every argument is a str.
  • parse_args() with no list reads sys.argv; in a notebook or test, pass a list.
  • argparse errors raise SystemExit(2), which except Exception does not catch. Catch SystemExit in tests (pytest.raises(SystemExit)), or use ArgumentParser(exit_on_error=False).
  • Compare Python versions as tuples: sys.version_info >= (3, 12). As strings, "3.9" > "3.12".
  • ~=1.9 allows 1.10; ~=1.9.0 does not.
  • pip install with a bare pip can target another Python. Use python -m pip or uv pip.
  • >= ranges alone do not make a run repeatable. Commit a lock file.
  • Moving .venv breaks it. Rebuild it from the lock file.
  • Pinning == in a library’s dependencies blocks its users’ resolver. Pin in lock files, not in libraries.