Skip to content

08. Modules, packages and environments

Until now, each program was one file. Real data work grows past one file fast: a loader, a cleaning step, a report and a command to run them. This module shows how Python finds and loads code from other files, how to group files into a package, how to give the package a command-line interface and how to describe its dependencies so that anyone can rebuild the same environment.

The running example is salesreport, a small real package that reads data/sales.csv and prints a revenue report. You build it file by file and run it with python -m salesreport data/sales.csv --top 3.

  • Import modules in four ways and explain what Python does during an import: sys.path, sys.modules and the one-time run of the module code.
  • Use if __name__ == "__main__": so that a file works both as a script and as an importable module.
  • Lay out a package with __init__.py, __main__.py and relative imports, and run it with python -m.
  • Read and write a pyproject.toml: name, version, Python version, dependencies, entry points and the build system.
  • Build a command-line interface with argparse: positional and optional arguments, types, choices, defaults, flags and --help.
  • Explain what a virtual environment contains, check which one is active and pin dependencies with requirements files and lock files.

A module is a file of Python code that other code can load. Every .py file is a module. The module name is the file name without .py: the file revenue_tools.py is the module revenue_tools.

Each module has its own namespace: a table that maps names to values. A function called load in one module does not clash with a function called load in another module. You reach a name inside a module with a dot: math.sqrt means “the name sqrt in the namespace of the module math”. A name that you reach with a dot is an attribute.

Modules come from three places:

Source Examples How you get it
Your own files revenue_tools.py, salesreport/ you write them
The standard library: the modules that ship with Python math, csv, json, pathlib, argparse always there
Third-party packages: code from other people, installed from the Python Package Index numpy, pandas, sklearn uv pip install or uv add

Why split code into modules? Three reasons:

  • Reuse. One load_sales() function serves the report script, the notebook and the tests.
  • Order. A 2,000-line script is hard to read. Ten files of 200 lines, each with one job, are easy.
  • Testing. You can import one function and test it without running the whole program (module 14).

The import statement loads a module and gives you a name for it.

import math
import statistics as st
from pathlib import Path
from csv import DictReader, reader
revenues = [66.49, 14.99, 19.99, 59.99]
print(math.fsum(revenues))
print(st.median(revenues))
print(Path("data/sales.csv").suffix)
print(DictReader.__name__, reader.__name__)
Output
161.46
39.99
.csv
DictReader reader
Form Gives you the name Use it when
import math math (then math.fsum) the default; the reader sees where each name comes from
import statistics as st st the module name is long, or a convention exists: import numpy as np, import pandas as pd
from pathlib import Path Path you use one or two names very often
from csv import * every public name of csv avoid it: a reader cannot see where a name comes from, and it can overwrite your names

PEP 8 puts imports at the top of the file, in three groups separated by a blank line: the standard library, third-party packages, then your own modules. The tool ruff sorts them for you with its import rules (ruff check --select I --fix).

Import order (PEP 8)
import csv # 1. standard library
from pathlib import Path
import pandas as pd # 2. third-party packages
from salesreport.stats import revenue_by # 3. your own code

The first time a program runs import salesreport, Python does four things:

  1. It looks in sys.modules, the module cache: a dictionary of every module that is already loaded. If the name is there, Python reuses that module and stops here.
  2. It searches the folders of sys.path, in order, for a file salesreport.py or a folder salesreport/.
  3. It creates a module object and runs the module code from top to bottom. Every def, every assignment and every print() at the top level runs now.
  4. It stores the module in sys.modules and binds the name salesreport in your namespace.
flowchart LR
    A["import salesreport"] --> B{"In sys.modules?"}
    B -- yes --> E["Bind the name"]
    B -- no --> C["Search sys.path"]
    C --> D["Run the module code once"]
    D --> F["Store in sys.modules"]
    F --> E

Step 3 has a consequence: top-level code in a module runs on import. The next section shows how to control that. Step 1 has another: a second import of the same module costs almost nothing and does not run the code again.

import json
import sys
print("json" in sys.modules)
print(sys.modules["json"] is json)
Output
True
True

If Python searches every folder and finds nothing, it raises ModuleNotFoundError. Module names are case-sensitive, like variable names:

import Pandas
Output
ModuleNotFoundError: No module named 'Pandas'

The two common causes are a typo and a package that is not installed in the active environment. Check both before anything else.

sys.path is the module search path: the list of folders that Python searches, in order. The first match wins. When you run python report.py, the list is:

  1. The folder that holds report.py. With python -m name, python -c or the REPL, it is the current working directory instead.
  2. The folders in the environment variable PYTHONPATH, if you set it (rarely needed).
  3. The standard library folders.
  4. The site-packages folder of the active environment, where installers put third-party packages.

This block prints the last part of each folder name after the first entry. The first entry is the project folder, so it differs on every computer:

from pathlib import Path
for folder in sys.path[1:]:
print(Path(folder).name)
Output
python313.zip
python3.13
lib-dynload
site-packages

python3.13 is the standard library and lib-dynload holds its compiled parts. Your names show your Python version. On Windows the names differ (DLLs, Lib), but the order is the same.

Because the script folder comes first, a file of yours can shadow (hide) a standard library module with the same name. This folder holds a file called csv.py next to a script that wants the real csv module:

shadowing/csv.py
# shadowing/csv.py: a file with the same name as a standard library module.
print("Running shadowing/csv.py, not the standard library csv module")
shadowing/read_orders.py
# shadowing/read_orders.py: wants the standard library csv module.
import csv
print("csv has DictReader:", hasattr(csv, "DictReader"))
Terminal
python shadowing/read_orders.py
Output
Running shadowing/csv.py, not the standard library csv module
csv has DictReader: False

Python found shadowing/csv.py first, ran it and never loaded the real module. The built-in function hasattr(obj, name) returns True when the object has an attribute with that name. A real script uses the attribute and crashes. Python 3.13 and newer add a hint to the error that names the file to rename:

shadowing/use_reader.py
# shadowing/use_reader.py: uses csv.DictReader, which the shadowing file lacks.
import csv
reader = csv.DictReader
Terminal
python shadowing/use_reader.py 2>&1 | tail -n 1 | cut -d "(" -f 1
Output
AttributeError: module 'csv' has no attribute 'DictReader'

cut -d "(" -f 1 keeps the text before the first (, because the rest of the line is long. On Python 3.13 and newer, the rest is a hint in parentheses that names the guilty file: (consider renaming '/path/to/my-course/shadowing/csv.py' since it has the same name as the standard library module named 'csv' and prevents importing that standard library module). Read that path first. Never name a file after a module you use: csv.py, statistics.py, random.py, pandas.py, test.py and code.py are the classic traps.

When Python imports one of your modules, it also saves a compiled copy in a folder called __pycache__ next to the file, so the next import starts faster. Python manages this folder by itself: it rebuilds the copy when the source changes and ignores it when the source is gone. You never need to edit or delete it; add __pycache__/ to .gitignore.

Every module has a variable __name__ (two underscores on each side; Python calls these names dunder names, short for “double underscore”). Python sets it before it runs the file:

  • When you run the file as a program, __name__ is the string "__main__".
  • When you import the file, __name__ is the module name.
where_am_i.py
# where_am_i.py: print the name that Python gives this file.
print("__name__ is", repr(__name__))
Terminal
python where_am_i.py
python -c "import where_am_i"
python -c "import where_am_i; import where_am_i"
Output
__name__ is '__main__'
__name__ is 'where_am_i'
__name__ is 'where_am_i'

The third command imports the module twice but prints once: the second import came from sys.modules. python -c "code" runs one line of code from the terminal.

The main guard is an if statement that runs code only when the file runs as a program:

The main guard
def main():
... # the work of the script
if __name__ == "__main__":
main()

With the guard, one file is two things at once: a script you can run, and a module whose functions other files can import without side effects. Put every action (reading files, printing, training a model) inside main() and call it under the guard. Example 1 shows the difference.

A package is a folder of modules that you import under one name. The folder holds a file called __init__.py. Python runs __init__.py when you import the package, so it is the place for the package’s version and for the names you want to offer at the top level.

This is the salesreport package that you build in this module:

Project folder
my-course/
├── data/
│ └── sales.csv
├── pyproject.toml
└── salesreport/ # the package
├── __init__.py # runs on "import salesreport"
├── __main__.py # runs on "python -m salesreport"
├── cli.py # argparse: read the command line
├── loader.py # read the CSV file
└── stats.py # totals and rankings
You write Python loads You can then use
import salesreport salesreport/__init__.py salesreport.load_sales, salesreport.__version__
import salesreport.stats __init__.py, then stats.py salesreport.stats.revenue_by
from salesreport.stats import revenue_by the same two files revenue_by
from salesreport import stats the same two files stats.revenue_by

A module inside a package is a submodule. A package inside a package is a subpackage: sklearn.linear_model is a subpackage of sklearn. The dotted name follows the folders.

Inside a package, a module imports its neighbors in one of two ways:

Kind Example in cli.py Meaning
Absolute import from salesreport.loader import load_sales the full dotted name from the top of the package
Relative import from .loader import load_sales . is “this package”, .. is “the parent package”

Both work. Relative imports keep working when you rename the package folder. They work only inside a package that Python imported as a package. That is why you run a package with python -m salesreport and never with python salesreport/cli.py:

Terminal
python salesreport/cli.py data/sales.csv 2>&1 | tail -n 1
Output
ImportError: attempted relative import with no known parent package

python salesreport/cli.py runs cli.py as a lone script, so it has no parent package and the dot means nothing. (2>&1 | tail -n 1 sends the error text to the normal output and keeps only its last line.)

python -m name runs a module by its module name, not by its file path. Python searches sys.path for it, imports its parent packages first and then runs it as __main__. For a package, python -m salesreport runs the file salesreport/__main__.py. You already use this form: python -m venv, python -m pip and python -m pytest all run a package’s __main__.py.

Two layouts are common:

Flat layout and src layout
flat layout src layout
my-project/ my-project/
├── pyproject.toml ├── pyproject.toml
├── salesreport/ ├── src/
│ └── __init__.py │ └── salesreport/
└── tests/ │ └── __init__.py
└── tests/
Flat layout src layout
Package folder at the project root inside src/
python -m salesreport from the root works at once works after you install the project
Protects against testing an uninstalled copy no yes
Good for scripts, analysis projects, this course libraries you publish, larger teams

The src layout puts the package outside sys.path[0]. Tests and scripts then cannot import the package folder by accident: you must install the project first, usually as an editable install (see below). Only tests that run against a built wheel catch a file that is missing from the package itself. uv init --package creates a src layout. This module uses the flat layout, because you can run it from the course folder without an install step.

pyproject.toml is the standard file that describes a Python project: its name, version, Python version, dependencies, commands and the tool that builds it. It is written in TOML, a simple configuration format with [sections] (called tables) and key = value lines. Installers (pip, uv), build tools and linters (ruff, mypy, pytest) all read it.

This is the real pyproject.toml of salesreport:

pyproject.toml
[project]
name = "salesreport"
version = "0.1.0"
description = "Summarize the revenue in a sales CSV file."
requires-python = ">=3.12"
license = "MIT"
authors = [{ name = "Ada Lovelace", email = "ada@example.com" }]
keywords = ["sales", "report", "csv"]
dependencies = []
[project.scripts]
salesreport = "salesreport.cli:main"
[dependency-groups]
dev = ["pytest>=9.2", "ruff>=0.17"]
[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"
Field Meaning
[project] The project’s metadata: data about the project. Its fields are a standard (PEP 621), so every tool reads them the same way.
name The name on the package index and in pip install salesreport. Use lowercase letters and - or _.
version The release number. 0.1.0 follows semantic versioning: MAJOR.MINOR.PATCH. Raise MAJOR for a breaking change, MINOR for a new feature, PATCH for a bug fix.
description One line for the package index and pip show.
requires-python The Python versions the code supports. An installer refuses to install the project on Python 3.11.
license The license as an SPDX identifier, a standard short name such as MIT or Apache-2.0.
authors A list of tables with a name and an email.
keywords Search words for the package index.
dependencies The third-party packages the code needs at run time. salesreport uses only the standard library, so the list is empty. A data project lists "pandas>=3.1" and so on.
[project.scripts] Entry points: terminal commands that the installer creates. salesreport = "salesreport.cli:main" means “the command salesreport calls the function main in the module salesreport.cli”.
[dependency-groups] Packages that only developers need, such as test and lint tools. They are not installed for users. uv sync installs the dev group by default.
[build-system] The build backend: the tool that turns the project folder into an installable package. requires lists what the installer must download to run it; build-backend names it. Hatchling, setuptools and uv_build are common choices.

A data analysis project has real dependencies. Its [project] table has lines like these:

pyproject.toml (dependencies of a data project)
requires-python = ">=3.12"
dependencies = [
"pandas>=3.1,<4",
"scikit-learn>=1.9",
"matplotlib>=3.11",
]

Tools add their settings in [tool.NAME] tables, for example [tool.ruff] with line-length = 88 or [tool.pytest] with testpaths = ["tests"] (pytest 9 reads this native table; older guides show the older form [tool.pytest.ini_options]). One file then configures the whole project.

The standard library reads TOML with tomllib (Python 3.11 and newer). Open the file in binary mode, "rb":

import tomllib
with open("pyproject.toml", "rb") as file:
config = tomllib.load(file)
project = config["project"]
print(project["name"], project["version"], project["requires-python"])
print(project["scripts"])
print(config["build-system"]["build-backend"])
Output
salesreport 0.1.0 >=3.12
{'salesreport': 'salesreport.cli:main'}
hatchling.build

TOML tables become dictionaries, TOML lists become lists, and strings, numbers and booleans become their Python types.

A command-line interface (CLI) is a way to control a program by typing a command in a terminal. You already use many: python report.py, uv pip install pandas, ruff check .. The words after the program name are command-line arguments. They let you run the same script on another file, another year or another number of rows without editing the code.

Python puts the arguments in the list sys.argv. The first item is the script name. Every item is a string:

show_argv.py
# show_argv.py: print the command-line arguments that Python received.
import sys
print("Script:", sys.argv[0])
print("Arguments:", sys.argv[1:])
Terminal
python show_argv.py data/sales.csv --top 3
Output
Script: show_argv.py
Arguments: ['data/sales.csv', '--top', '3']

Reading sys.argv by hand gets messy fast: which item is the path, is --top present, is "3" a valid number? The standard library module argparse does this work. You describe the arguments, and argparse reads sys.argv, converts the types, fills in defaults, checks the values, writes the --help text and prints a clear error for bad input.

There are three kinds of arguments. A flag is a special kind of option:

Kind Looks like Required? Example
Positional argument a bare value; its position gives its meaning yes, by default data/sales.csv
Optional argument (an option) starts with - or -- no, by default --top 3, --by region
Flag an option with no value; it switches a feature on no --share

parser.add_argument() describes one argument. Its most useful keyword arguments:

Keyword Does Example
type converts the text with this function type=int, type=float, type=Path
default the value when the option is missing default=5
choices the only allowed values choices=["category", "region", "channel"]
action="store_true" a flag: True when present, else False --share
help the text for --help; %(default)s inserts the default help="rows to show (default: %(default)s)"
metavar the placeholder name in the help text metavar="N" shows --top N
required=True makes an option mandatory rarely needed: use a positional instead
nargs how many values: "+" one or more, "*" zero or more, "?" zero or one nargs="+" for several files
import argparse
parser = argparse.ArgumentParser(prog="topsales", description="Rank sales groups.")
parser.add_argument("path", help="sales CSV file")
parser.add_argument("--top", type=int, default=5, help="rows to show")
parser.add_argument("--by", choices=["category", "region"], default="category")
parser.add_argument("--share", action="store_true", help="show percentages")
args = parser.parse_args(["data/sales.csv", "--top", "3", "--share"])
print(args)
print(args.top + 1, type(args.top).__name__)
Output
Namespace(path='data/sales.csv', top=3, by='category', share=True)
4 int

parse_args() returns a Namespace: a simple object with one attribute per argument. The option --top becomes args.top. A dash inside a name becomes an underscore: --min-revenue becomes args.min_revenue. Here you pass a list to parse_args() to test the parser inside Python. With no list, it reads the real command line, sys.argv[1:].

argparse also writes the help text. format_help() returns the text that --help prints:

print(parser.format_help())
Output
usage: topsales [-h] [--top TOP] [--by {category,region}] [--share] path
Rank sales groups.
positional arguments:
path sales CSV file
options:
-h, --help show this help message and exit
--top TOP rows to show
--by {category,region}
--share show percentages

Every program has a -h/--help option for free. When the input is wrong, argparse prints the usage line and an error message to standard error (stderr: the second output stream of a program, meant for errors) and stops the program with exit code 2. An exit code (or exit status) is the number that a program returns to the terminal when it ends: 0 means success, any other number means failure. Scripts, schedulers and CI systems read it to decide what to do next.

The start-here page Virtual environments created .venv with one command. Here is what that folder holds and how Python uses it.

A virtual environment has three parts:

Part macOS and Linux Windows Holds
Interpreter and commands .venv/bin/ .venv\Scripts\ python, activate and every command that packages install (ruff, pytest, salesreport)
Packages .venv/lib/python3.13/site-packages/ .venv\Lib\site-packages\ the third-party packages of this project
Configuration .venv/pyvenv.cfg .venv\pyvenv.cfg the base Python it came from and whether it can see the system packages

The environment does not copy the standard library. Its python is a link (or a tiny launcher on Windows) to the base Python, the installation that created it. When that python starts, it finds pyvenv.cfg one folder above it, uses the base Python’s standard library and adds the environment’s own site-packages to sys.path. So an environment is cheap: a few files plus the packages you install.

Python records both places:

  • sys.prefix is the folder of the environment that runs now.
  • sys.base_prefix is the folder of the base Python.

They differ only inside a virtual environment:

print("Environment folder:", Path(sys.prefix).name)
print("Inside a virtual environment:", sys.prefix != sys.base_prefix)
Output
Environment folder: .venv
Inside a virtual environment: True

Activation changes nothing inside .venv. The activate script puts .venv/bin first in your PATH, so the command python finds the environment’s interpreter first. You can skip activation and call the interpreter by its path, .venv/bin/python report.py. Schedulers and servers often do exactly that. uv run also skips it: it finds .venv in the project and uses it.

The Python Package Index (PyPI, pypi.org) is the public server that hosts third-party packages. Installers download a wheel from it: a .whl file, a ready-built zip archive of a package that the installer unpacks into site-packages. If no wheel fits your system, the installer downloads the source code and builds a wheel with the project’s build backend.

Two installers matter:

  • pip comes with most Python installations. Run it as python -m pip, so it installs into the Python you mean.
  • uv is a newer and much faster tool. It installs packages (uv pip ..., the same commands as pip) and also manages whole projects (uv add, uv lock, uv sync, uv run).

Each command below needs the network, so this page does not run them.

Terminal
uv init # create pyproject.toml (add --package for a src layout)
uv add pandas # add to dependencies, update uv.lock, install
uv add --dev pytest ruff # add to [dependency-groups] dev
uv remove pandas # remove from pyproject.toml and the environment
uv lock # resolve every dependency and write uv.lock
uv sync # make .venv match uv.lock exactly
uv run python -m salesreport data/sales.csv # sync, then run in .venv
uv tree # show the dependency tree

An editable install (-e .) installs your own project so that the environment points to your source folder instead of a copy. You edit the code and the next run uses the change, with no reinstall. It also creates the entry-point commands from [project.scripts]: after uv pip install -e ., you can type salesreport data/sales.csv instead of python -m salesreport data/sales.csv. uv sync does an editable install of the project for you when pyproject.toml has a [build-system] table, as the one of salesreport does. A project without one (a plain uv init application) gets its dependencies but is not installed itself.

A dependency is a package that your code needs. A direct dependency is one you list yourself, such as pandas. A transitive dependency is a dependency of a dependency: scikit-learn needs NumPy, SciPy, joblib and threadpoolctl, among others. You never asked for threadpoolctl, but scikit-learn breaks without it. A project with 5 direct dependencies often installs 40 packages.

A version specifier says which versions are acceptable:

Specifier Allows Typical use
pandas==3.1.1 exactly 3.1.1 (a pin) requirements files and lock files of an application
pandas>=3.1 3.1 or newer the minimum you need, for a library
pandas>=3.1,<4 3.1 up to, but not including, 4.0 protect against the next breaking release
pandas~=3.1 the “compatible release”: >=3.1, ==3.* the same as above, shorter
pandas~=3.1.1 >=3.1.1, ==3.1.*: bug fixes only very cautious
pandas!=3.0.2 anything except 3.0.2 skip one broken release
tzdata; sys_platform == "win32" only on Windows an environment marker: a condition on the system

The installer’s resolver reads every specifier, of your project and of every package, and picks one version of each package that satisfies all of them. Dependency resolution can fail when two packages want incompatible versions; the installer then prints which requirements conflict.

Ranges let your project accept bug fixes. But a range alone does not make a run repeatable: pandas>=3.1 gives 3.1.1 today and 3.2.0 next month. To get the same environment on every computer and in every year, record the exact version of every package, transitive ones included. These files describe dependencies; the first gives ranges, the last three record exact versions:

File Written by Holds Use
pyproject.toml dependencies you direct dependencies, as ranges what the code needs
requirements.txt (pinned) you, pip freeze or uv pip compile a list of name==version lines a simple, universal list for pip or uv
uv.lock uv lock, uv add, uv sync every package, the exact version, the download hashes, for every platform the full record of a uv project
pylock.toml uv export, the experimental pip lock the same, in a newer standard format (PEP 751) a lock file that different tools can share

A lock file is a file that records the exact version of every direct and transitive dependency, often with a hash (a fingerprint of the file) so the installer can prove that it downloaded the same bytes. Commit pyproject.toml and the lock file to version control. Never commit .venv: it is large, tied to one computer and easy to rebuild from the lock file.

flowchart LR
    P["pyproject.toml<br/>pandas>=3.1"] --> R["Resolver<br/>uv lock"]
    R --> L["uv.lock<br/>pandas 3.1.1, numpy 2.5.4, ..."]
    L --> S["uv sync"]
    S --> V[".venv<br/>exact versions"]

The course itself follows this rule: requirements.txt on the start-here page pins every library with ==, so your output matches the output on this site.

A requirements file is a plain text list of requirements that pip install -r and uv pip install -r read. It is older and simpler than a lock file, and every Python tool understands it. Each line has one of a few forms:

requirements-dev.txt
# Tools for developers, on top of the run-time pins.
-r requirements.txt
-c constraints.txt
pytest==9.2.0
ruff==0.17.4
tzdata==2026.6 ; sys_platform == "win32"
-e .
Line Meaning
# ... a comment; the installer skips it, also after a requirement
-r requirements.txt include every line of another requirements file; a common split is requirements.txt for run time and requirements-dev.txt for tools
-c constraints.txt a constraints file: it limits the versions of packages that get installed for another reason, but installs nothing by itself
pytest==9.2.0 a requirement with a version specifier
... ; sys_platform == "win32" an environment marker: only on Windows
-e . an editable install of the project in this folder

You rarely write the full pinned list by hand. Write the direct dependencies, with ranges, in a short input file, requirements.in, and let a tool resolve and pin everything:

Terminal
uv pip compile requirements.in -o requirements.txt
uv pip compile requirements.in -o requirements.txt --generate-hashes

The output starts like this. Every package has an exact pin, and each # via comment says which package needs it:

requirements.txt (start, written by uv pip compile)
# This file was autogenerated by uv via the following command:
# uv pip compile requirements.in -o requirements.txt
cloudpickle==3.1.2
# via joblib
contourpy==1.4.0
# via matplotlib
joblib==1.6.0
# via scikit-learn
numpy==2.5.4
# via
# contourpy
# matplotlib
# pandas
# scikit-learn
# scipy
pandas==3.1.1
# via -r requirements.in

With --generate-hashes, each pin also gets the file hash (a SHA-256 fingerprint) of every file that may be downloaded. A \ at the end of a line continues it on the next line:

requirements.txt (one line with hashes)
threadpoolctl==3.8.0 \
--hash=sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137 \
--hash=sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da
# via scikit-learn

As soon as one line has a hash, pip switches to hash-checking mode (also available as pip install --require-hashes): it refuses any file whose fingerprint differs and any requirement without a hash. This protects you against a changed or tampered download.

Example 1 — Turn a helper script into a reusable module

Section titled “Example 1 — Turn a helper script into a reusable module”

Goal: Two scripts compute order-line revenue. Move the formula into one module, revenue_tools.py, that you can run as a self-test and also import from a daily check script without side effects.

Step 1 — Write the module with a main guard

Section titled “Step 1 — Write the module with a main guard”
revenue_tools.py
"""revenue_tools.py: helpers for the revenue of order lines."""
def line_revenue(unit_price, quantity, discount=0.0):
"""Return the revenue of one order line, rounded to cents."""
return round(unit_price * quantity * (1 - discount), 2)
def main():
"""A quick self-test with line 1 of data/sales.csv."""
print("Self-test:", line_revenue(69.99, 1, 0.05))
if __name__ == "__main__":
main()

The module defines functions only. The self-test lives in main() and runs only under the main guard. The first line of data/sales.csv is a Cotton Bed Sheet Set at 69.99 USD, 1 unit, 5% discount, revenue 66.49.

Terminal
python revenue_tools.py
Output
Self-test: 66.49

Run as a program, the file has __name__ == "__main__", so main() runs. The result equals the revenue column of the file, so the formula is right.

Step 3 — Import the module from another script

Section titled “Step 3 — Import the module from another script”
daily_check.py
"""daily_check.py: use revenue_tools as a module."""
import revenue_tools
print("Imported module:", revenue_tools.__name__)
print("This script:", __name__)
print("Line revenue:", revenue_tools.line_revenue(249.00, 3, 0.1))
Output
Imported module: revenue_tools
This script: __main__
Line revenue: 672.3

import revenue_tools found the file in the script’s folder, sys.path[0]. Its __name__ is revenue_tools, so the self-test did not run. Only daily_check.py is __main__.

Step 4 — See what happens without the guard

Section titled “Step 4 — See what happens without the guard”
revenue_tools.py (no guard)
def line_revenue(unit_price, quantity, discount=0.0):
return round(unit_price * quantity * (1 - discount), 2)
print("Self-test:", line_revenue(69.99, 1, 0.05)) # runs on every import

With this version, python daily_check.py prints Self-test: 66.49 first, before its own lines. In a real project the top-level code is worse than a print: it reads a large file or trains a model every time a test imports one function.

Common mistakes:

  • Writing if __name__ == "main": without the underscores. The condition is never true, so the script silently does nothing. Copy the guard exactly: "__main__".
  • Putting the script’s work at the top level “for now”. Every import then runs it. Put it in main() from the start.
  • Naming the module after a library, such as statistics.py. It shadows the standard library module for every script in the folder.

Example 2 — Find out where an import comes from

Section titled “Example 2 — Find out where an import comes from”

Goal: A colleague says “pandas 3 is installed”, but the script behaves like pandas 2. Find which environment runs, which version of each package it loads and whether a project file shadows a module.

Step 1 — Check the interpreter and the environment

Section titled “Step 1 — Check the interpreter and the environment”
import sys
from pathlib import Path
print(f"Python {sys.version_info.major}.{sys.version_info.minor}")
print("Environment:", Path(sys.prefix).name)
print("Virtual environment:", sys.prefix != sys.base_prefix)
Output
Python 3.13
Environment: .venv
Virtual environment: True

sys.version_info holds the version of the interpreter that runs the code, as numbers. Path(sys.prefix).name is the name of the environment folder. If it is not your project’s .venv, the script runs in another environment, with other packages. This is the first check for any “but it is installed!” problem.

Step 2 — Ask the installed packages for their versions

Section titled “Step 2 — Ask the installed packages for their versions”
from importlib.metadata import version
for name in ["numpy", "pandas", "scikit-learn"]:
print(f"{name}=={version(name)}")
Output
numpy==2.5.4
pandas==3.1.1
scikit-learn==1.9.1

importlib.metadata.version() reads the version from the distribution metadata: the information that the installer saved next to each package in site-packages. It takes the distribution name that you install (scikit-learn), which can differ from the import name (sklearn). The output has the format of a pinned requirements file.

import csv
import pandas
print(Path(csv.__file__).name)
print(Path(pandas.__file__).parent.name, Path(pandas.__file__).parent.parent.name)
Output
csv.py
pandas site-packages

A module’s __file__ attribute holds the path of the file that Python loaded. csv is a single file in the standard library. pandas is a package: its __init__.py sits in the folder pandas, inside site-packages. Print the full __file__ on your computer to see which environment it comes from; this page prints only the last parts, because the full path differs on every computer.

Step 4 — Check the project for shadowing names

Section titled “Step 4 — Check the project for shadowing names”
project_files = ["report.py", "statistics.py", "loader.py", "random.py", "csv.py"]
stems = [Path(name).stem for name in project_files]
shadowing = sorted(stem for stem in stems if stem in sys.stdlib_module_names)
print("These files shadow the standard library:", shadowing)
Output
These files shadow the standard library: ['csv', 'random', 'statistics']

sys.stdlib_module_names is a set of the names of every standard library module. Path(name).stem is the file name without its suffix. The check finds three bad names; rename them, for example to sales_stats.py.

Common mistakes:

  • Running pip install in one terminal and python from another environment. Check sys.prefix in the script that fails, not in a new terminal.
  • Using the import name with version(). version("sklearn") raises PackageNotFoundError. Use the name you installed: version("scikit-learn").
  • Printing pandas.__version__ and trusting it more than the environment check. Both are useful: the version tells you what loaded, sys.prefix tells you from where.

Example 3 — Build the salesreport package

Section titled “Example 3 — Build the salesreport package”

Goal: Turn the sales report logic into a package with one job per module: loader.py reads data/sales.csv, stats.py aggregates and __init__.py offers the main functions at the top level.

salesreport/loader.py
"""Read a sales CSV file into a list of dictionaries."""
import csv
from pathlib import Path
# Columns that hold numbers, and the function that converts each one.
NUMBER_COLUMNS = {
"unit_price": float,
"quantity": int,
"discount": float,
"revenue": float,
}
def load_sales(path, year=None):
"""Return the rows of a sales CSV file, with the numbers converted.
With a year, keep only the order lines of that year.
"""
rows = []
with Path(path).open(newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
if year is not None and not row["order_date"].startswith(str(year)):
continue
for column, convert in NUMBER_COLUMNS.items():
row[column] = convert(row[column])
rows.append(row)
return rows

csv.DictReader gives each line as a dict of strings (module 07). The dict NUMBER_COLUMNS maps each numeric column to its conversion function, so one loop converts them all. The module only defines things: importing it reads no file.

salesreport/stats.py
"""Aggregate sales rows: totals, groups and rankings."""
def total_revenue(rows):
"""Return the summed revenue of all rows, rounded to cents."""
return round(sum(row["revenue"] for row in rows), 2)
def revenue_by(rows, column):
"""Return {group: revenue} for one column, largest revenue first."""
totals = {}
for row in rows:
group = row[column]
totals[group] = totals.get(group, 0.0) + row["revenue"]
ranked = sorted(totals.items(), key=lambda item: item[1], reverse=True)
return {group: round(revenue, 2) for group, revenue in ranked}
def top_n(totals, n):
"""Return the first n items of a ranked {group: value} dict."""
return dict(list(totals.items())[:n])

stats.py knows nothing about files. It works on any list of row dicts, so a test can pass three hand-made rows. A dict keeps the order in which you insert keys, so the ranked order survives.

salesreport/__init__.py
"""salesreport: summarize the course sales file from the command line.
Run it with: python -m salesreport data/sales.csv
"""
from .loader import load_sales
from .stats import revenue_by, top_n, total_revenue
__version__ = "0.1.0"
__all__ = ["load_sales", "revenue_by", "top_n", "total_revenue"]

The relative imports pull the main functions up to the package level, so users write from salesreport import load_sales and do not need to know which file holds it. __version__ is the usual place for the version. __all__ lists the public names: the names that from salesreport import * gives and that documentation tools show.

import salesreport
from salesreport import load_sales, revenue_by, top_n, total_revenue
rows = load_sales("data/sales.csv")
print("Version:", salesreport.__version__)
print("Order lines:", len(rows))
print("Revenue:", total_revenue(rows))
print(top_n(revenue_by(rows, "region"), 2))
Output
Version: 0.1.0
Order lines: 20228
Revenue: 3596523.83
{'East': 993683.72, 'South': 891766.07}

The folder salesreport/ sits in the working folder, which is on sys.path, so the import works with no install. The 20,228 lines and the total of 3,596,523.83 USD match the dataset. East leads the regions.

rows_2023 = load_sales("data/sales.csv", year=2023)
print(len(rows_2023), total_revenue(rows_2023))
print(rows_2023[0]["order_date"], rows_2023[-1]["order_date"])
Output
9081 1645589.59
2023-01-01 2023-12-31

The year parameter keeps the 9,081 lines of 2023. The string test startswith("2023") works because the dates are ISO text, YYYY-MM-DD.

Common mistakes:

  • Forgetting __init__.py. Python then treats the folder as a namespace package; imports still work, but there is no place for __version__ and some tools skip the folder.
  • Importing cli.py from __init__.py. Keep __init__.py small: import only what users need, or every import of the package pays for everything.
  • Two modules that import each other at the top level (a circular import). Python then finds a half-finished module and raises ImportError: cannot import name .... Move the shared code into a third module.

Example 4 — Give the package a command-line interface

Section titled “Example 4 — Give the package a command-line interface”

Goal: Let an analyst run the report from the terminal, choose the grouping column and the number of rows, filter a year and add percentages, with a helpful --help and clear errors.

salesreport/cli.py
"""The command-line interface: read the arguments, build the report, print it."""
import argparse
from pathlib import Path
from . import __version__
from .loader import load_sales
from .stats import revenue_by, top_n, total_revenue
GROUP_COLUMNS = ["category", "region", "channel"]
def positive_int(text):
"""Convert text to an int of at least 1. argparse calls it for --top."""
value = int(text)
if value < 1:
raise argparse.ArgumentTypeError(f"must be at least 1, got {value}")
return value
def build_parser():
"""Return the argument parser of the salesreport command."""
parser = argparse.ArgumentParser(
prog="salesreport",
description="Summarize the revenue in a sales CSV file.",
epilog="Example: python -m salesreport data/sales.csv --by region --top 3",
)
parser.add_argument("path", type=Path, help="CSV file with one row per order line")
parser.add_argument(
"--by",
choices=GROUP_COLUMNS,
default="category",
help="column to group by (default: %(default)s)",
)
parser.add_argument(
"--top",
type=positive_int,
default=5,
metavar="N",
help="show the N largest groups (default: %(default)s)",
)
parser.add_argument("--year", type=int, help="keep only the orders of this year")
parser.add_argument(
"--share", action="store_true", help="add each group's share of the total"
)
parser.add_argument(
"--version", action="version", version=f"%(prog)s {__version__}"
)
return parser
def format_report(rows, by, top, share=False):
"""Return the report as a list of text lines."""
total = total_revenue(rows)
ranked = top_n(revenue_by(rows, by), top)
lines = [
f"Sales report: {len(rows):,} order lines, revenue {total:,.2f} USD",
f"Top {len(ranked)} by {by}:",
]
for rank, (group, revenue) in enumerate(ranked.items(), start=1):
line = f"{rank:>2}. {group:<12} {revenue:>14,.2f}"
if share:
line += f" {revenue / total:>7.1%}"
lines.append(line)
return lines
def main(argv=None):
"""Run the command. argv=None means: read the real command line."""
parser = build_parser()
args = parser.parse_args(argv)
if not args.path.is_file():
parser.error(f"file not found: {args.path}")
rows = load_sales(args.path, year=args.year)
if not rows:
year_text = f" for year {args.year}" if args.year is not None else ""
parser.error(f"no order lines{year_text}")
for line in format_report(rows, args.by, args.top, args.share):
print(line)
return 0

The module has four functions with one job each. positive_int is a custom type: argparse calls it with the text and shows its ArgumentTypeError message. build_parser() only describes the arguments. format_report() returns lines instead of printing them, so a test can check them. main() connects the parts and returns the exit code 0. parser.error() prints the usage and a message to stderr and exits with code 2.

salesreport/__main__.py
"""Run the package as a program: python -m salesreport ..."""
from .cli import main
raise SystemExit(main())

python -m salesreport runs this file. raise SystemExit(main()) ends the program with the return value of main() as its exit code. The file needs no main guard, because Python only runs it for python -m.

Terminal
python -m salesreport data/sales.csv --top 3
Output
Sales report: 20,228 order lines, revenue 3,596,523.83 USD
Top 3 by category:
1. Electronics 1,808,108.17
2. Home 672,294.61
3. Sports 544,108.55

The positional data/sales.csv became args.path, a Path. --top 3 became the int 3. --by was missing, so it took its default, category. Electronics is half of all revenue.

Terminal
python -m salesreport data/sales.csv --by region --year 2024 --share
Output
Sales report: 11,147 order lines, revenue 1,950,934.24 USD
Top 4 by region:
1. East 544,765.09 27.9%
2. South 482,265.00 24.7%
3. North 477,729.41 24.5%
4. West 446,174.74 22.9%

Options can come in any order. --share is a flag: present, so args.share is True. The default --top 5 asks for more groups than exist, and the header reports the 4 it found.

Terminal
python -m salesreport --help
Output
usage: salesreport [-h] [--by {category,region,channel}] [--top N] [--year YEAR] [--share]
[--version]
path
Summarize the revenue in a sales CSV file.
positional arguments:
path CSV file with one row per order line
options:
-h, --help show this help message and exit
--by {category,region,channel}
column to group by (default: category)
--top N show the N largest groups (default: 5)
--year YEAR keep only the orders of this year
--share add each group's share of the total
--version show program's version number and exit
Example: python -m salesreport data/sales.csv --by region --top 3

argparse built every line from the add_argument() calls: the choices, the metavar N, the defaults through %(default)s and the epilog at the end. The text wraps to your terminal width, so your lines can break in other places.

Step 6 — See the errors and the exit codes

Section titled “Step 6 — See the errors and the exit codes”
Terminal
python -m salesreport data/sales.csv --top 0 2>&1
echo "exit code: $?"
python -m salesreport data/sales.csv --by city 2>&1 | tail -n 1
python -m salesreport data/missing.csv 2>&1 | tail -n 1
python -m salesreport --version
Output
usage: salesreport [-h] [--by {category,region,channel}] [--top N] [--year YEAR] [--share]
[--version]
path
salesreport: error: argument --top: must be at least 1, got 0
exit code: 2
salesreport: error: argument --by: invalid choice: 'city' (choose from category, region, channel)
salesreport: error: file not found: data/missing.csv
salesreport 0.1.0

Each bad input stops the program before it reads any data, with a message that names the argument. 2>&1 sends the error stream to the normal output, so the lines appear in order. $? holds the exit code of the last command in bash and zsh; it is 2 for every argparse error. In PowerShell, the exit code is in $LASTEXITCODE.

Common mistakes:

  • Forgetting type=int. args.top is then the string "3", and list(...)[:args.top] raises TypeError: slice indices must be integers or None or have an __index__ method.
  • Using type=bool for a yes/no option. bool("False") is True, so the option is always on. Use action="store_true".
  • Calling sys.exit() deep inside helper functions. Return values or raise exceptions instead, and let main() decide the exit code. Helpers then stay usable in tests and notebooks.

Example 5 — Test the command-line interface from Python

Section titled “Example 5 — Test the command-line interface from Python”

Goal: Check the parser and the report without a terminal, as a test or a notebook would, by passing argument lists to parse_args() and main().

from salesreport.cli import build_parser, format_report, main, positive_int
parser = build_parser()
args = parser.parse_args(["data/sales.csv", "--by", "channel", "--top", "2"])
print(args)
print(type(args.path).__name__, args.top, args.share)
Output
Namespace(path=PosixPath('data/sales.csv'), by='channel', top=2, year=None, share=False)
PosixPath 2 False

parse_args() takes the same words that you type in the terminal, as a list of strings. PosixPath is the Path type on macOS and Linux; on Windows it is WindowsPath. --year and --share were not given: year is None (an option with no default) and share is False (a flag).

Step 2 — Call main() with an argument list

Section titled “Step 2 — Call main() with an argument list”
exit_code = main(["data/sales.csv", "--by", "channel", "--share"])
print("exit code:", exit_code)
Output
Sales report: 20,228 order lines, revenue 3,596,523.83 USD
Top 2 by channel:
1. store 2,077,057.36 57.8%
2. online 1,519,466.47 42.2%
exit code: 0

main(argv) runs the whole program inside Python. This is the reason for the argv=None parameter: the terminal passes nothing and argparse reads sys.argv, while a test passes its own list. Online orders bring 42.2% of the revenue.

Step 3 — Test the custom type function alone

Section titled “Step 3 — Test the custom type function alone”
print(positive_int("3"), positive_int("12"))
Output
3 12
positive_int("0")
Output
argparse.ArgumentTypeError: must be at least 1, got 0

positive_int is an ordinary function, so you can test it directly. argparse catches its ArgumentTypeError and turns it into the error: argument --top: ... message of Example 4.

rows = [
{"category": "Books", "revenue": 30.0},
{"category": "Home", "revenue": 45.0},
{"category": "Books", "revenue": 20.0},
]
lines = format_report(rows, "category", top=1)
for line in lines:
print(line)
assert lines[-1].startswith(" 1. Books")
Output
Sales report: 3 order lines, revenue 95.00 USD
Top 1 by category:
1. Books 50.00

Three hand-made rows are enough to test the grouping and the ranking: the two Books rows add up to 50.0, which beats Home at 45.0. You can work out the right answer by hand, so the check is trustworthy. Module 14 turns checks like this into pytest tests.

Common mistakes:

  • Calling parser.parse_args() with no list inside a test or a notebook. It then reads the test runner’s own arguments and fails with a strange error.
  • Expecting except Exception to catch a bad value. argparse prints the error and raises SystemExit(2), which is not a subclass of Exception. In a test, catch SystemExit explicitly (pytest: pytest.raises(SystemExit)), test the type functions directly as in Step 3, or build the parser with ArgumentParser(exit_on_error=False), which raises argparse.ArgumentError for most bad values instead.
  • Printing inside format_report(). Return the lines; let main() print them.

Example 6 — Look inside a virtual environment

Section titled “Example 6 — Look inside a virtual environment”

Goal: Create a throwaway environment, look at its folders and prove that it is isolated from the course environment.

Step 1 — Create an environment without a network

Section titled “Step 1 — Create an environment without a network”
Terminal
python -m venv demo-env --without-pip
ls demo-env
ls demo-env/bin
Output
bin
include
lib
pyvenv.cfg
activate
activate.csh
activate.fish
Activate.ps1
python
python3
python3.13

python -m venv runs the standard library’s venv module. --without-pip skips installing pip, so the command needs no download. On Windows, the commands live in demo-env\Scripts and the list includes python.exe, activate.bat and Activate.ps1. The folder name python3.13 follows your Python version. On Linux, ls demo-env also shows lib64, a link to lib.

Terminal
grep -E "include-system|^version" demo-env/pyvenv.cfg
Output
include-system-site-packages = false
version = 3.13.7

pyvenv.cfg names the base Python (the home line, not shown here because it holds a full path) and its version. include-system-site-packages = false means that the environment cannot see the packages of the base Python.

Terminal
demo-env/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)"
demo-env/bin/python -c "import pandas" 2>&1
python -c "import pandas; print('course environment has pandas', pandas.__version__)"
Output
True
Traceback (most recent call last):
File "<string>", line 1, in <module>
import pandas
ModuleNotFoundError: No module named 'pandas'
course environment has pandas 3.1.1

The new environment is a virtual environment, and it has no pandas: its site-packages is empty. The course environment, which runs the plain python command, has pandas 3.1.1. Two folders on one computer, two different sets of packages.

Terminal
rm -rf demo-env
test -d demo-env || echo "demo-env is gone"
Output
demo-env is gone

An environment is disposable. If one breaks, delete the folder and rebuild it from requirements.txt or uv.lock. On Windows, delete the folder in the file explorer or with Remove-Item -Recurse demo-env in PowerShell.

Common mistakes:

  • Moving or renaming an environment folder. Its scripts hold absolute paths, so they break. Delete and recreate it instead.
  • Committing .venv to Git. Python 3.13’s venv and uv venv write a .gitignore with * inside the environment folder, so Git skips it. Add .venv/ to the project’s .gitignore too, for older Pythons and other tools, and commit the lock file instead.
  • Expecting deactivate or a new terminal to remove packages. Activation only changes PATH; the packages stay in the folder.

Example 7 — Describe an analysis project and pin its dependencies

Section titled “Example 7 — Describe an analysis project and pin its dependencies”

Goal: A colleague must rerun your churn analysis next year with the same results. The analysis imports pandas, scikit-learn and matplotlib. Read its project description, pin the direct dependencies, follow the transitive ones and produce the full pinned file.

import tomllib
ANALYSIS_PYPROJECT = """
[project]
name = "churn-analysis"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = ["pandas>=3.1,<4", "scikit-learn>=1.9", "matplotlib>=3.11"]
[dependency-groups]
dev = ["pytest>=9.2", "ruff>=0.17"]
"""
config = tomllib.loads(ANALYSIS_PYPROJECT)
project = config["project"]
for key in ["name", "version", "requires-python", "dependencies"]:
print(f"{key:16} {project[key]}")
print(f"{'dev group':16} {config['dependency-groups']['dev']}")
Output
name churn-analysis
version 1.0.0
requires-python >=3.12
dependencies ['pandas>=3.1,<4', 'scikit-learn>=1.9', 'matplotlib>=3.11']
dev group ['pytest>=9.2', 'ruff>=0.17']

tomllib.loads() parses TOML text; in a real project you would tomllib.load() the file. The dependencies are ranges: they say what the analysis accepts, not what it ran with. The :16 format spec pads each key to 16 characters, so the values line up.

Step 2 — Write pinned lines for the direct dependencies

Section titled “Step 2 — Write pinned lines for the direct dependencies”
direct = ["pandas", "scikit-learn", "matplotlib"]
pins = [f"{name}=={version(name)}" for name in direct]
print("\n".join(pins))
Output
pandas==3.1.1
scikit-learn==1.9.1
matplotlib==3.11.2

These three lines are a valid requirements.txt. They pin the packages that the analysis imports. They are not enough: each of them needs other packages.

Step 3 — List the run-time requirements of pandas

Section titled “Step 3 — List the run-time requirements of pandas”
from importlib.metadata import requires
for requirement in requires("pandas"):
if "extra ==" not in requirement:
print(requirement)
Output
numpy>=2.0.2; python_version < "3.14"
numpy>=2.3.3; python_version >= "3.14"
python-dateutil>=2.9.0
tzdata; sys_platform == "win32"
tzdata; sys_platform == "emscripten"

requires() returns the dependency specifiers that pandas declared in its metadata. Lines with extra == belong to optional extras such as pandas[excel], so the loop skips them. NumPy needs a newer minimum on Python 3.14. The tzdata lines have environment markers: they apply only on Windows and in the browser (emscripten).

Step 4 — Follow the dependencies of scikit-learn

Section titled “Step 4 — Follow the dependencies of scikit-learn”
needs = [r for r in requires("scikit-learn") if "extra ==" not in r]
print(needs)
print("threadpoolctl", version("threadpoolctl"))
Output
['numpy>=1.24.1', 'scipy>=1.10.0', 'joblib>=1.4.0', 'narwhals>=2.0.1', 'threadpoolctl>=3.5.0']
threadpoolctl 3.8.0

scikit-learn needs five packages. Your analysis never imports threadpoolctl (it controls how many CPU threads NumPy uses) or narwhals, yet scikit-learn fails without them, and each of them has its own requirements. Nobody wrote them in a requirements file. A lock file (uv lock) or a full pin (uv pip compile, pip freeze) records them with their exact versions. Then a colleague runs uv sync or uv pip sync requirements.txt and gets the same environment.

requirements.in
pandas>=3.1,<4
scikit-learn>=1.9
matplotlib>=3.11
Terminal
uv pip compile requirements.in -o requirements.txt
requirements.txt (written by uv pip compile)
# This file was autogenerated by uv via the following command:
# uv pip compile requirements.in -o requirements.txt
cloudpickle==3.1.2
# via joblib
contourpy==1.4.0
# via matplotlib
cycler==0.12.1
# via matplotlib
fonttools==4.68.0
# via matplotlib
joblib==1.6.0
# via scikit-learn
kiwisolver==1.5.1
# via matplotlib
matplotlib==3.11.2
# via -r requirements.in
narwhals==2.28.0
# via scikit-learn
numpy==2.5.4
# via
# contourpy
# matplotlib
# pandas
# scikit-learn
# scipy
packaging==26.3
# via matplotlib
pandas==3.1.1
# via -r requirements.in
pillow==13.0.0
# via matplotlib
pyparsing==3.3.3
# via matplotlib
python-dateutil==4.0.0
# via
# matplotlib
# pandas
scikit-learn==1.9.1
# via -r requirements.in
scipy==1.18.1
# via scikit-learn
threadpoolctl==3.8.0
# via scikit-learn
tzdata==2026.6
# via python-dateutil

Three direct dependencies became 18 pinned packages. The command needs the package index, so this page does not run it; the file above came from the course environment’s versions. Commit requirements.in and requirements.txt. Your colleague runs uv pip sync requirements.txt and gets exactly these 18 versions. In a uv project, uv add pandas scikit-learn matplotlib writes the ranges into pyproject.toml and the pins into uv.lock in one step.

Common mistakes:

  • Pinning only the direct dependencies and calling it reproducible. A new release of a transitive dependency can still change results.
  • Pinning == in the dependencies of a library that others install. Their resolver then cannot fit your pins next to their other packages. Libraries use ranges; applications and analyses use lock files.
  • Editing uv.lock by hand. Change pyproject.toml (or run uv add) and let uv lock rewrite it.
Mistake Symptom Fix
A project file named like a module: csv.py, random.py, pandas.py AttributeError: module 'csv' has no attribute 'DictReader' Rename the file; the 3.13+ error hint names it
Package installed in another environment ModuleNotFoundError: No module named 'pandas' Activate the right environment; check sys.prefix; install with python -m pip or uv pip
if __name__ == "main": The script runs and prints nothing Write "__main__" with two underscores on each side
Script work at the top level of a module Imports are slow, print things or read files Move the work into main() under the main guard
python salesreport/cli.py with relative imports ImportError: attempted relative import with no known parent package Run python -m salesreport from the project folder
python -m salesreport from the wrong folder No module named salesreport cd to the folder that contains salesreport/, or install the project with -e .
Two modules import each other ImportError: cannot import name ... (most likely due to a circular import) Move the shared code into a third module
from module import * Names appear from nowhere or overwrite yours Import the names you need, or the module
type=bool in add_argument() --flag False still gives True action="store_true"
No type=int on a numeric option TypeError when the value is used as a number Add type=int or type=float
parse_args() with no list in a notebook or test error: unrecognized arguments Pass a list: parse_args(["data/sales.csv"])
pip install with a bare pip command The package lands in another Python python -m pip install ... or uv pip install ...
Only pandas>=3.1 in the project and no lock file A colleague gets other versions and other results Commit uv.lock, or a fully pinned requirements.txt
.venv committed or copied to another computer Broken paths, huge repository Ignore .venv/; rebuild it with uv sync
  • Web development: a Django or FastAPI project is a package of modules (models.py, views.py, routes/). pyproject.toml lists its dependencies and uv.lock makes every server install the same versions.
  • Automation and DevOps: backup scripts and deploy tools are argparse CLIs that a scheduler such as cron calls with arguments and judges by their exit code.
  • Tooling: pip, pytest and black are packages whose commands come from entry points in [project.scripts]. uv and ruff are compiled programs whose packages install their commands in the same folder. python -m http.server 8000 and python -m json.tool data/config.json run standard library packages as tools.
  • Teams and CI: a continuous integration server (a machine that tests every change) creates a fresh environment from the lock file for each run, so a test failure means a code problem, not a version difference.
  • A module is a .py file with its own namespace. import searches sys.path, runs the module code once and caches it in sys.modules.
  • Prefer import module or from module import name. Avoid import *. Never name a file after a module you use.
  • __name__ is "__main__" when a file runs as a program. Put the script’s work in main() under if __name__ == "__main__":.
  • A package is a folder with __init__.py. Inside it, use relative imports (from .loader import load_sales) and run it with python -m package, which runs __main__.py.
  • pyproject.toml describes the project: [project] metadata and dependencies, [project.scripts] entry points, [dependency-groups] dev tools and [build-system].
  • argparse turns sys.argv into a Namespace: positional arguments, options with type, choices and default, flags with store_true, and a free --help. Errors exit with code 2.
  • A virtual environment is a folder with links to a base Python, its own site-packages and pyvenv.cfg. sys.prefix != sys.base_prefix inside one. Activation only changes PATH.
  • Ranges in pyproject.toml say what the code accepts. A lock file (uv.lock) or a full pin list records every direct and transitive version, so the environment can be rebuilt exactly.

Q1. A module cleaning.py has a print("loaded") line at the top level. Two files in the same program both run import cleaning. How many times does loaded appear, and why?

Answer

Once. The first import runs the module code and stores the module in sys.modules. The second import finds it there and reuses it without running the code again.

Q2. What is the value of __name__ in report.py when you run python report.py, and when another file runs import report?

Answer

"__main__" when you run it, "report" when it is imported. The main guard if __name__ == "__main__": uses this difference.

Q3. A file statistics.py sits in your project folder. What goes wrong in a script in the same folder that runs import statistics and calls statistics.mean()?

Answer

The script’s folder is first in sys.path, so Python imports your statistics.py instead of the standard library module. statistics.mean does not exist in your file, so the call raises AttributeError. Rename the file.

Q4. Why does python salesreport/cli.py fail when cli.py contains from .loader import load_sales, and what command works?

Answer

Run by its path, cli.py is a lone script with no parent package, so the relative import has nothing to be relative to: ImportError: attempted relative import with no known parent package. python -m salesreport imports the package first, so the relative import works. (python -m salesreport.cli imports correctly too, but runs nothing, because cli.py has no main guard.)

Q5. In [project.scripts], what does salesreport = "salesreport.cli:main" do?

Answer

It defines an entry point. When you install the project, the installer creates a command salesreport in the environment’s bin (or Scripts) folder. The command imports salesreport.cli and calls main(), and the return value becomes the exit code.

Q6. Write the add_argument() call for an option --min-revenue that takes a decimal number with the default 0.0. Which attribute holds the value?

Answer

parser.add_argument("--min-revenue", type=float, default=0.0). The value is in args.min_revenue: argparse turns the dash into an underscore.

Q7. Why is type=bool wrong for an on/off option, and what should you use?

Answer

argparse calls bool() on the text, and every non-empty string is truthy, so --verbose False gives True. Use action="store_true": the flag is True when present and False when absent.

Q8. How can a script check that it runs inside a virtual environment?

Answer

Compare sys.prefix with sys.base_prefix. They differ only inside a virtual environment. Path(sys.prefix).name shows the environment’s folder name, for example .venv.

Q9. Your pyproject.toml says pandas>=3.1. Why can a colleague still get different results next year, and what file prevents it?

Answer

>=3.1 allows any newer pandas, and the transitive dependencies (NumPy, python-dateutil and others) are not fixed at all. A lock file such as uv.lock, or a requirements file that pins every package with ==, records the exact versions, so uv sync rebuilds the same environment.

Q10. What does pandas~=3.1 allow? And pandas~=3.1.1?

Answer

~=3.1 means >=3.1 and ==3.*: any 3.x release from 3.1 on, but not 4.0. ~=3.1.1 means >=3.1.1 and ==3.1.*: only bug-fix releases of 3.1.

Q11. What is the difference between a direct and a transitive dependency? Give an example from the course stack.

Answer

A direct dependency is one you list and import yourself, such as pandas. A transitive dependency is needed by one of your dependencies: scikit-learn needs threadpoolctl. Your code never imports threadpoolctl, but it must be installed.

Q12. What does an exit code of 2 from python -m salesreport tell a scheduler?

Answer

The program failed. 0 means success and any other value means failure. argparse uses 2 for a usage error, such as a bad option value or a missing file reported with parser.error().

Your progress

0 / 4 done

  • Exercises: 27 exercises on imports, the main guard, packages, argparse, environments and pins, with hints and full solutions.
  • Mini-project: build sensorcheck, a package with a CLI that checks the sensor readings.
  • Cheat sheet: imports, packages, pyproject.toml, argparse, venv, uv and pip on one page.
  • Next module: 09. Standard library power tools tours collections, itertools, functools, datetime, re and more of the modules you now know how to import.