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.
Quick lookup
Section titled “Quick lookup”| 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 . |
Imports
Section titled “Imports”| 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 jsonimport sysfrom importlib.metadata import versionfrom pathlib import Path
import pandas as pd
print(sys.modules["json"] is json) # a module is loaded once, then cachedprint(pd.__name__, version("pandas")) # the alias keeps the real nameprint(Path(pd.__file__).parent.parent.name) # third-party code lives in site-packagesprint("csv" in sys.stdlib_module_names) # is it a standard library name?Truepandas 3.1.1site-packagesTruePEP 8 order: standard library, a blank line, third-party packages, a blank line, your own modules. ruff check --select I --fix sorts them.
The import system
Section titled “The import system”| 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 |
__name__ and the main guard
Section titled “__name__ and the main guard”| 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" |
"""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())Packages
Section titled “Packages”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 |
python -m
Section titled “python -m”| 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
Section titled “pyproject.toml”[project]name = "salesreport" # distribution name (pip install salesreport)version = "0.1.0" # MAJOR.MINOR.PATCHdescription = "Summarize the revenue in a sales CSV file."requires-python = ">=3.12" # installers refuse older Pythonslicense = "MIT" # SPDX identifierauthors = [{ 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 buildbuild-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"])['pandas>=3.1,<4'] {'salesreport': 'salesreport.cli:main'}argparse
Section titled “argparse”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 argparsefrom pathlib import Path
parser = argparse.ArgumentParser(prog="topsales", description="Rank sales groups.")parser.add_argument("path", type=Path) # positional, converted to Pathparser.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_revenueparser.add_argument("--share", action="store_true") # flagparser.add_argument("--sensor", action="append") # repeatable -> listparser.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())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] pathformat_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 subcommandstop = 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"]))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 |
Virtual environments
Section titled “Virtual environments”| 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 sysfrom pathlib import Path
print(Path(sys.prefix).name) # the environment that runs nowprint(sys.prefix != sys.base_prefix) # True inside a virtual environmentprint(sys.version_info >= (3, 12)) # compare versions as tuples, never as strings.venvTrueTrue- Activation only puts
.venv/binfirst inPATH..venv/bin/python file.pyanduv runwork without it. - An environment cannot be moved or renamed. Delete it and rebuild it.
- Never commit
.venv. Add.venv/to.gitignore.
pip and uv commands
Section titled “pip and uv commands”These commands need the network or change your environment, so they are shown, not run.
# --- environments ---uv venv --python 3.13 # create .venvpython -m venv .venv # the same with the standard library
# --- uv project workflow (pyproject.toml + uv.lock) ---uv init # new project; --package for a src layoutuv add "pandas>=3.1" # add a dependency, lock, installuv add --dev pytest # add to [dependency-groups] devuv remove pandas # remove a dependencyuv lock # resolve and write uv.lockuv lock --upgrade-package pandas # allow a newer pandas in the lockuv sync # make .venv match uv.lock exactlyuv sync --locked # fail if uv.lock is out of date (CI)uv run python -m salesreport data/sales.csvuv tree # dependency treeuv export --output-file requirements.txt # lock -> pinned requirements fileuv 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 projectuv pip list # installed packagesuv pip show pandas # details and dependencies of one packageuv pip freeze > requirements.txt # exact versions of everything installeduv pip compile pyproject.toml -o requirements.txt # pin all dependenciesuv pip sync requirements.txt # install exactly the list, remove the restuv pip uninstall pandasRequirements files
Section titled “Requirements files”# a comment; also allowed after a requirement-r requirements.txt # include another requirements file-c constraints.txt # cap versions; installs nothing itselfpytest==9.2.0 # requirement with a pintzdata==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:
pandas==3.1.1 # via -r requirements.inthreadpoolctl==3.8.0 # via scikit-learnWith --generate-hashes, every pin also lists the SHA-256 hash of each allowed file:
threadpoolctl==3.8.0 \ --hash=sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137 \ --hash=sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da # via scikit-learnVersion specifiers and pins
Section titled “Version specifiers and pins”| 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)])~=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 |
Gotchas
Section titled “Gotchas”- A file named
csv.py,random.py,statistics.py,email.pyorpandas.pyin 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()underif __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. Runpython -m pkg. python -m pkgmust run from the folder that containspkg/, 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=boolin argparse makes--flag Falsetruthy. Useaction="store_true".- argparse stores
--min-revenueasargs.min_revenue. - Without
type=, every argument is astr. parse_args()with no list readssys.argv; in a notebook or test, pass a list.- argparse errors raise
SystemExit(2), whichexcept Exceptiondoes not catch. CatchSystemExitin tests (pytest.raises(SystemExit)), or useArgumentParser(exit_on_error=False). - Compare Python versions as tuples:
sys.version_info >= (3, 12). As strings,"3.9" > "3.12". ~=1.9allows 1.10;~=1.9.0does not.pip installwith a barepipcan target another Python. Usepython -m piporuv pip.>=ranges alone do not make a run repeatable. Commit a lock file.- Moving
.venvbreaks it. Rebuild it from the lock file. - Pinning
==in a library’sdependenciesblocks its users’ resolver. Pin in lock files, not in libraries.