01A.7 Modules, Packages, Imports and a Tour of the Standard Library
So far every lesson has been a single file. Real programs are never one file: they are collections of modules (one .py file each) grouped into packages (folders with an __init__.py), importing each other and leaning on the standard library — the hundreds of modules that ship inside Python itself. This lesson teaches the whole machinery: how import finds and runs code, how to organise a project so the imports keep working, how third-party packages and virtual environments keep dependencies from fighting each other, and a working tour of the standard library modules you will actually meet in AI engineering — each one with a runnable example. It ends by assembling the support-ticket toolkit from the earlier lessons into a proper triage package you run with python -m triage.
What you'll learn
- What a module is, the three import forms (
import x,from x import y,import x as y), and whyimport *is a trap - How Python finds modules:
sys.path,sys.modules,PYTHONPATH, and how to ask the import system where a module would come from - Module caching — in
sys.modulesand on disk in__pycache__—importlib.reload,__all__, module docstrings, andif __name__ == "__main__"withpython -m - Packages:
__init__.py, namespace packages (PEP 420), flat vssrc/layouts, stdlib name shadowing,__main__.pyand entry points - The import failure modes you will actually hit: relative vs absolute imports, circular imports (with the real traceback, including how the message changed in Python 3.13), and import cost with lazy imports
- Third-party packages and virtual environments: PyPI,
pipvsuv,python -m venv, activation on macOS/Linux/Windows,requirements.txtvspyproject.toml, pinning, dependency hell, and supply-chain hygiene - A tour of the standard library —
pathlib,os,sys,shutil,tempfile,json,csv,sqlite3,datetime/zoneinfo/time,collections,itertools,functools,re,string,textwrap,math/statistics/random,decimal/fractions,uuid,hashlib,base64,secrets,urllib,argparse,subprocess, the concurrency modules by name,logging,configparser/tomllib, archives,warnings,pprint,html,xml.etree,abc,contextlib,unittest— each with a runnable example, and a decision table for when the standard library is enough - How to explore any module yourself with
dir(),help()andsys.stdlib_module_names
What you don't need
- Any third-party package installed. Everything in this lesson is standard library only — that is the point of the tour.
- Any API key, account or network access. No API key needed.
- Deep file/JSON/CSV knowledge: 01A.9 owns that; this lesson shows the modules exist and how to reach for them. Type hints are previewed only (01A.10 owns them); exceptions get a preview here and a full treatment in 01A.8.
Setup
You need Python 3.11 or newer and a terminal. The recommended route is uv, which installs and runs Python for you (as of November 2026 the current stable Python is 3.15.x; anything from 3.11 up runs every sample here):
curl -LsSf https://astral.sh/uv/install.sh | sh # macOS/Linux; see https://docs.astral.sh/uv/ for Windows
uv python install 3.13
uv run python --versionPiping a script straight into a shell (curl ... | sh) means "download code from the internet and immediately execute it as you" — convenient, and a real risk if the download is tampered with or the domain is spoofed. The URL above is uv's official installer channel (HTTPS, served by Astral, the tool's maker), but the habit is worth understanding: you can instead download first and inspect — curl -LsSf https://astral.sh/uv/install.sh -o uv-install.sh, read it, then sh uv-install.sh — or skip the script entirely with brew install uv on macOS or the standalone binaries on the uv install page. For everything else in this lesson, no installs are needed at all: the standard library is already inside your Python.
Or install from python.org or your OS package manager and run scripts with python3 script.py. If terminal or editor setup is new, Module 00, lesson 00.1 walks through it, and lesson 03.1, §4.1 has the same uv setup in the LLM-API context. Every code block below names the file it belongs to; save it and run it from that folder.
What you must be able to do after this lesson#
- Import code with the three import forms and say why import * is a trap
- Explain how Python finds a module using sys.path
- Create a package with init.py
- Fix a circular import
- Create and activate a virtual environment and install a package
- Pick a standard library module for a common task
Why this matters for an AI engineer#
Almost every line of code in Modules 01B to 14 stands on what this lesson teaches. SDK clients are modules you import; your own code is organised into packages; configuration is read with tomllib; cache keys are hashlib digests; CLIs are built with argparse; batch jobs shell out through subprocess; and "it works on my machine" is usually a virtual-environment problem.
| You'll hear... | You'll understand it after... |
|---|---|
"Just pip install it into your venv." |
Part 4: Third-party packages and virtual environments |
"Put it in src/ and make it a proper package." |
2.3 Project layouts |
| "That's a circular import — move the shared code down." | 3.2 Circular imports |
| "Hash the canonical request for the cache key." | 5.7 Encoding, hashing and identifiers and 11B.3 §3.2 |
"Never shell=True, pass an argv list." |
5.9 Command lines and processes |
"The agent's shell tool is just subprocess with guards." |
5.9 and 08A.15 §2.3 |
| "Pin your dependencies and check for typosquats." | 4.5 Supply-chain hygiene and 12.7 §5 |
"Read the config with tomllib." |
5.11 The long tail and 01B.2 |
| "SQLite is in the stdlib — no server needed." | 5.3 Data formats and 00.7 |
Part 1: Modules — code you can import#
1.1 A module is a file#
A module is simply a .py file. Its filename (minus .py) is its module name: greeter.py is the module greeter. Everything at the top level of that file — functions, classes, constants, even variables — becomes attributes you can reach from other files. There is no special declaration, no registration step: Python's rule is "a file is a module".
Two files, side by side:
# greeter.py — a tiny module: one public function and one constant.
"""A tiny module: one public function and one constant."""
GREETING = "Hello from the greeter module"
def greet(name: str) -> str:
return f"{GREETING}, {name}!"# main.py — the three everyday import forms, side by side.
import greeter # form 1: import the module, use module.attr
from greeter import greet # form 2: import a name directly
import greeter as g # form 3: import with an alias
print(greeter.greet("Ada"))
print(greet("Grace"))
print(g.GREETING)Run python3 main.py from the folder containing both files:
Hello from the greeter module, Ada!
Hello from the greeter module, Grace!
Hello from the greeter module1.2 The three import forms, and the one to avoid#
import json # module object; use json.dumps(...)
import json as js # same, shorter alias — rare for stdlib, common for long names
from json import dumps # just the function; dumps(...)
from json import dumps, loads # several names at once
from collections import ( # parenthesised multi-line import
Counter,
defaultdict,
)Rules of thumb that keep codebases readable:
- Prefer
import moduleorfrom package import modulewhen you will use several of its names — the dotted access (json.dumps) documents where each call comes from. from x import yis fine for one or two names and for re-exporting in__init__.py(Part 2).import x as yearns its keep for genuinely long module names (from xml.etree import ElementTree as ETis the classic) or to disambiguate two modules with the same name. Aliasingjsontojsjust to save four keystrokes makes grep and refactoring harder.- Never
from x import *in application code — 1.5 explains why.
1.3 The module search path: sys.path, sys.modules, PYTHONPATH#
When you write import greeter, Python asks: where is greeter? The answer is a search path — an ordered list of directories checked top to bottom. You can see your own interpreter's list:
# showpath.py — prove sys.path[0] is "this script's directory".
import os
import sys
from pathlib import Path
script_dir = Path(sys.argv[0]).resolve().parent
print("sys.path[0] is script dir ->", Path(sys.path[0]).resolve() == script_dir)
print("script file ->", Path(sys.argv[0]).name)
print("python >= 3.11 ->", sys.version_info >= (3, 11))sys.path[0] is script dir -> True
script file -> showpath.py
python >= 3.11 -> Truesys.path[0] itself is an absolute path — print it and you will see your own script's folder (the basename shown above is whatever you named things, which is why the check compares paths instead). sys.path[0] is the directory of the script you ran (or '', meaning "the current directory", for python3 -c and the interactive interpreter). After it come, in order: directories named in the PYTHONPATH environment variable, the standard-library directories, and finally the site-packages directory where pip/uv install third-party packages. The first directory containing greeter.py wins — later copies are ignored.
Prove it: two folders, patha/ and pathb/, each holding a different who.py (ANSWER = "first on sys.path" and ANSWER = "second on sys.path"):
$ PYTHONPATH=patha:pathb python3 -c "import who; print(who.ANSWER)"
first on sys.path
$ PYTHONPATH=pathb:patha python3 -c "import who; print(who.ANSWER)"
second on sys.path
$ cd pathb && PYTHONPATH=../patha python3 -c "import who; print(who.ANSWER)"
second on sys.path(On Windows PowerShell the separator is ; not : and the variable is set differently: $env:PYTHONPATH = "patha;pathb" — it persists for the session until you clear it with $env:PYTHONPATH = $null.)
The third command is the subtle one: the current directory (for -c, sys.path[0] is '') is searched before PYTHONPATH, so running from inside pathb picks pathb's copy even though patha is listed first in PYTHONPATH. Order matters, and "current directory first" is why a stray json.py in your project silently replaces the standard library's json — demonstrated in 3.1 and the mistake gallery.
Two more pieces of machinery:
sys.modulesis the cache of already-imported modules, keyed by name.import xtwice, orimport xafterfrom x import y, runs the file once; afterwards the entry insys.modulesis reused. That is why module-level code (prints, connections opened at import time) runs at most once per process — and whyimportlib.reloadexists (1.4).PYTHONPATHis the environment-variable way to add search directories without touching code. It is convenient for scratch experiments and a smell in production code, where the project layout (Part 2) should make imports work with no environment help at all.
1.4 Module caching and importlib.reload#
# counter.py — used to demonstrate importlib.reload.
"""Counter module used to demonstrate importlib.reload."""
calls = 0
def bump() -> int:
global calls
calls += 1
return calls# reload_demo.py — import once, call, reload, call again.
import importlib
import counter
print("first import :", counter.bump(), counter.bump())
# Editing counter.py on disk would NOT change the already-loaded module
# object. reload() re-reads the file and re-executes it.
counter.calls = 99 # pretend the old module carried stale state
importlib.reload(counter)
print("after reload, calls =", counter.calls) # back to 0: module re-ran
print("bump() ->", counter.bump())first import : 1 2
after reload, calls = 0
bump() -> 1The mental model: import counter runs the file and stores the module object in sys.modules["counter"]. Editing the file afterwards changes nothing — the object in memory is what every import counter returns. importlib.reload(counter) re-reads the file and re-executes it into the same module object, so attribute lookups through the module (counter.bump) see the new contents (and module-level state resets, as calls did above). One subtlety: names already bound by from counter import bump keep pointing at the old function object — reload does not reach into other modules' namespaces. Another reason it is a dev tool, not a production pattern.
Caching has a second layer you will see on disk: the first time Python imports a .py file it compiles it to bytecode and writes a .pyc file under a __pycache__/ directory next to the source. The .pyc filename carries a tag for the exact interpreter (counter.cpython-314.pyc on Python 3.14, counter.cpython-311.pyc on 3.11), so caches from different versions never collide. On later imports Python compares the .pyc's recorded source timestamp and size against the .py file and reuses the bytecode only if they match — edit the source and the next import silently recompiles. If the import fails partway, no .pyc is written; a missing or stale .pyc is never an error, just a recompile.
# pycache_demo.py — the on-disk bytecode cache, __pycache__.
import importlib.util
from pathlib import Path
import counter # importing a local module writes __pycache__/counter.*.pyc
cache_dir = Path(counter.__file__).parent / "__pycache__"
pyc = sorted(cache_dir.glob("counter.*.pyc"))
print("pyc count ->", len(pyc))
print("name ends .pyc ->", pyc[0].suffix == ".pyc")
print("cache_from_source ->", pyc[0] == Path(importlib.util.cache_from_source(counter.__file__)))
print("bump works ->", counter.bump())pyc count -> 1
name ends .pyc -> True
cache_from_source -> True
bump works -> 1importlib.util.cache_from_source is the function that computes the .pyc path for a given .py — the same lookup the import system uses. Three ways to turn bytecode writing off when you want to: the -B flag (python3 -B script.py), the PYTHONDONTWRITEBYTECODE=1 environment variable, or sys.dont_write_bytecode = True before importing. Read-only source trees and some CI images set one of these so __pycache__ never appears. (If a __pycache__ folder ever looks suspicious, it is safe to delete — Python rebuilds it.)
1.5 __all__, module docstrings and the import * question#
Every module has a docstring (the first string literal — greeter.__doc__ returns it) and a set of dunder attributes (__name__, __file__, __doc__, __all__...) that describe it. help(greeter) in the REPL or pydoc greeter renders them; dir(greeter) lists its names.
__all__ is the module's way of saying "these are my public names". It matters for exactly one thing: from module import *. Without __all__, a star import grabs every name not starting with an underscore — including imported helpers the module never meant to share. With __all__, only the listed names come across:
# star.py — a module with __all__ and a private helper, for the star-import demo.
"""Module with __all__ and a private helper, for the star-import demo."""
__all__ = ["public_one", "public_two"]
def public_one() -> str:
return "one"
def public_two() -> str:
return "two"
def _private_helper() -> str:
return "you should not see me via star import"# star_demo.py — what `from star import *` actually brings in.
from star import *
print("public_one ->", public_one())
print("public_two ->", public_two())
print("'public_one' in dir() ->", "public_one" in dir())
# _private_helper is not in __all__, so the star import skipped it:
print("has _private_helper ->", hasattr(__import__("star"), "_private_helper"))
try:
print(_private_helper())
except NameError as e:
print("calling it ->", type(e).__name__, e)public_one -> one
public_two -> two
'public_one' in dir() -> True
has _private_helper -> True
calling it -> NameError name '_private_helper' is not definedRead that carefully: _private_helper exists in the module (hasattr is True) — the star import simply refused to bind it, because __all__ did not list it. Calling it then fails with NameError.
1.6 if __name__ == "__main__" and python -m#
Every module has a __name__. When you run a file directly, Python sets __name__ to the string "__main__". When you import it, __name__ is the module's real name. That one fact powers the standard "only run this when executed, not when imported" guard:
# tool.py — a module with the __main__ guard: run directly AND import it.
"""Module with the __main__ guard: run directly AND import it."""
def main() -> None:
print("main() is running")
if __name__ == "__main__":
print(f"__name__ is {__name__!r}: running as a script")
main()
else:
print(f"__name__ is {__name__!r}: imported as a module")$ python3 tool.py
__name__ is '__main__': running as a script
main() is running
$ python3 -m tool
__name__ is '__main__': running as a script
main() is running
$ python3 import_tool.py # import_tool.py contains: import tool
__name__ is 'tool': imported as a moduleThree ways to "run" the same file, two different __name__s. The guard is how a file can be both an importable module (functions other code reuses) and a runnable script (a demo, a CLI, a test fixture) without side effects leaking into importers. Put setup, main() calls and sys.exit(...) inside the guard; keep functions and classes at top level.
python3 -m tool deserves a note: -m means "run this module". Python finds tool on sys.path, imports it as __main__, and — crucially — sets sys.path[0] to the current directory rather than the script's directory. For single files the difference is invisible; for packages it is essential (2.5).
1.7 Import cost and lazy imports#
Imports are not free: import numpy can take hundreds of milliseconds and tens of megabytes; even import json parses and executes a file. Two consequences:
- Startup time matters for CLIs. A tool that imports heavy modules at the top pays that cost on every invocation, even
--help. - Import side effects are real. A module that opens a file, starts a thread or reads config at top level does so at import time — which may be earlier than you expect (e.g. when pytest collects your test file).
The fix is the lazy import: import inside the function that needs it, the first time it runs:
# lazy_demo.py — proof that imports cost memory only when they happen.
import sys
print("before: 'json' loaded?", "json" in sys.modules)
def load_json_lazily():
import json # happens on first call, not at module import time
return json.dumps({"ok": True})
print("still before call :", "json" in sys.modules)
print("result :", load_json_lazily())
print("after first call :", "json" in sys.modules)before: 'json' loaded? False
still before call : False
result : {"ok": true}
after first call : Truesys.modules is the receipt: json was absent until the function ran. Use lazy imports for heavy or rarely-needed dependencies (numpy/pandas in a CLI that mostly parses text, provider SDKs in a tool with offline modes). Don't scatter them everywhere — top-level imports are clearer, and circular-import problems are easier to spot. A middle path is a small _imports.py or function-level import with a comment saying why.
Part 2: Packages#
A package is a directory that contains modules — and, by convention, an __init__.py file that marks it as one. import mypkg then runs mypkg/__init__.py, and mypkg.core refers to mypkg/core.py. Packages are how a single-file script grows into a project: related modules live together under one importable name.
2.1 __init__.py — the package's front door#
__init__.py runs when the package is first imported, exactly once (same caching rules as modules). Its two jobs:
- Re-export the package's public API so users can write
from mypkg import Ticketinstead offrom mypkg.core import Ticket. - Hold package-level state or setup — version strings, registries, default configuration.
# mypkg/__init__.py — a real package: __init__.py re-exports the useful names.
"""A real package: __init__.py re-exports the useful names."""
from mypkg.core import Ticket, priority_of # noqa: F401 (re-exported on purpose)
__all__ = ["Ticket", "priority_of"]
__version__ = "0.1.0"# mypkg/core.py — core types of the demo package.
"""Core types of the demo package."""
from dataclasses import dataclass
@dataclass
class Ticket:
ticket_id: str
subject: str
priority: int = 3
def priority_of(ticket: Ticket) -> int:
return ticket.priority# use_pkg.py — a package is imported by its top-level name.
import mypkg
print("version ->", mypkg.__version__)
t = mypkg.Ticket("T-1", "Printer offline", priority=1)
print("ticket ->", t)
print("priority->", mypkg.priority_of(t))
print("has core ->", hasattr(mypkg, "core")) # submodule attribute exists after importversion -> 0.1.0
ticket -> Ticket(ticket_id='T-1', subject='Printer offline', priority=1)
priority-> 1
has core -> TrueNote hasattr(mypkg, "core") is True: importing mypkg ran __init__.py, which imported mypkg.core — and importing a submodule always sets it as an attribute of the parent package. That is why import mypkg.core and import mypkg followed by mypkg.core.X behave the same.
2.2 Namespace packages (PEP 420)#
Since Python 3.3, a directory without __init__.py can still be imported — it becomes a namespace package. This exists mainly so that pieces of one logical package can be spread across directories (for example, google/cloud/... contributed by several distributions). For your own code, treat it as "works, but don't rely on it": always write __init__.py, because it makes the package explicit, gives you the re-export front door, and avoids surprises when two directories on sys.path happen to share a name.
Proof that it works — nspkg/sub/mod.py with no __init__.py anywhere:
# nspkg_demo.py — PEP 420: directories without __init__.py are importable.
from pathlib import Path
import nspkg.sub.mod as m
print("imported ->", m.__name__)
print("file tail ->", Path(m.__file__).name) # Path handles '/' and '\' alikeimported -> nspkg.sub.mod
file tail -> mod.pynspkg.sub.mod imported cleanly even though neither nspkg/ nor nspkg/sub/ had an __init__.py. The directories became namespace packages automatically.
2.3 Project layouts: flat vs src/#
Once a script becomes a real project, where do the files go? Two layouts cover almost everything:
flat layout src layout (recommended for packages)
----------- ------------------------------------
myproject/ myproject/
├── main.py ├── pyproject.toml
├── helpers.py ├── src/
├── tests/ │ └── mypkg/
│ └── test_helpers.py │ ├── __init__.py
└── data/ │ ├── core.py
│ └── cli.py
└── tests/
└── test_core.py| Flat layout | src/ layout |
|
|---|---|---|
| Import works because... | the project root is on sys.path when you run python main.py from it |
an installed/packaged copy is used |
| Risk | import mypkg can silently pick up a different mypkg folder elsewhere on sys.path (your repo root is always first for scripts) |
none — the source tree is not on sys.path, so only the installed package resolves |
| Tests import the package... | the way users will not get it (repo checkout, not the built artifact) | exactly the way end users get it |
| Best for | scripts, small tools, learning | anything packaged, shared, or installed with pip install -e . |
The src/ layout's superpower is isolation: because src/mypkg is not on sys.path during development, import mypkg can only succeed if the package was actually installed (editable install puts a link in site-packages). Tests then verify the real install path, not a happy accident of directory position. This is why essentially every serious Python project — including the ones in later modules — uses src/.
Other conventions worth copying: tests/ at the top level (never inside the package — it is not shipped code), scripts/ or tools/ for one-off utilities, data files inside the package under a data/ subpackage or referenced by path, and a README.md at the root. The triage package at the end of this lesson uses a flat layout deliberately — it is a teaching example run from its own folder, and the src/ trade-off is explained where it matters (01B.1).
2.4 Naming: avoiding stdlib shadowing#
Module and package names share one namespace with the entire standard library and every installed package. Naming your file json.py, random.py, email.py, types.py, code.py or test.py means your file wins over the real thing whenever it sits earlier on sys.path — and it will sit earlier, because the script's directory is sys.path[0].
Demonstration: a local json.py containing only a marker, next to shadow_demo.py:
# json.py — a local file that shadows the standard-library json module.
"""A local file that shadows the standard-library json module.
Delete this file (or rename it) and `import json` finds the real one again.
"""
ORIGIN = "local shadow copy"# shadow_demo.py — which json did we actually get?
from pathlib import Path
import json
print("module file ->", Path(json.__file__).name)
print("marker ->", getattr(json, "ORIGIN", "(real stdlib json)"))module file -> json.py
marker -> local shadow copyimport json found your json.py, not the standard library's — and nothing warned you. json.dumps would have failed later with AttributeError, far from the cause.
Practical rules:
- Before naming a module, check it is not a stdlib name:
python3 -c "import sys; print('json' in sys.stdlib_module_names)"(the full set is in 5.1) — or just tryimportlib.util.find_spec("json")(3.3). - Names at real risk: anything in the stdlib (
json,csv,email,http,types,code,random,string,time,calendar,copy,io,re— built-in modules such assysare found beforesys.pathis consulted, so those cannot be shadowed this way), plus common third-party names (pandas.py,numpy.py,requests.py,click.py,yaml.py). - If you must shadow deliberately (vendoring a patched copy), rename the import in your code (
import json as stdlib_jsonwon't help — the damage is already done atimport jsonresolution). The fix is always: rename your file. - Python 3.11 added a safety switch:
python3 -P script.py(or the environment variablePYTHONSAFEPATH=1) stops Python from prepending the script's directory (the current directory for-m, an empty entry for-c) tosys.path, so a strayjson.pynext to your script can no longer hijack the standard library. The price is that plain sibling imports (import helpersfrom the same folder) stop working unless the code is a proper package, which is one more argument for the layouts in 2.3. The default is unchanged, so code you share must not depend on the switch. - The same trap works in reverse for packages: a folder named
testsorscriptsis fine, but a top-level package namedemailorhttpwill break every library that imports the real one.
2.5 python -m package, __main__.py and entry points#
Drop a file named __main__.py inside a package and python3 -m package runs that file as __main__ — the package's official "run me" entry point:
# relpkg/__main__.py — entry point for `python3 -m relpkg`.
"""Entry point for `python3 -m relpkg`."""
from relpkg.core import greet_all
def main() -> None:
for name in ("Ada", "Grace", "Linus"):
print(greet_all(name))
if __name__ == "__main__":
main()# relpkg/core.py — package core: the greeting logic.
"""Package core: the greeting logic."""
def greet_all(name: str) -> str:
return f"Hello, {name} — from relpkg.core"$ python3 -m relpkg
Hello, Ada — from relpkg.core
Hello, Grace — from relpkg.core
Hello, Linus — from relpkg.coreWhy -m and not python3 relpkg/__main__.py? Because -m imports the package properly: relpkg is on sys.path, __main__.py can use relative imports (from .core import greet_all), and sys.path[0] is the current directory — so sibling data files and the package itself resolve the way they do for installed tools. Running __main__.py by path puts relpkg/ itself on sys.path and breaks import relpkg.
The production version of this idea is the console-script entry point: in pyproject.toml you declare [project.scripts] triage = "triage.cli:main", and installing the package creates a triage command that calls triage.cli.main(). The triage package at the end of this lesson declares exactly that — you will see the wiring in Part 7. Entry-point mechanics belong to 01B.1; the takeaway here is that __main__.py + python -m is the zero-installation version of the same trick.
Part 3: Import pitfalls#
Imports fail in a small number of recurring ways. This part is the field guide; the mistake gallery collects the tracebacks.
3.1 Absolute vs relative imports#
An absolute import names the full path from a top-level package: from relpkg.core import shout. A relative import starts with dots meaning "from here": . = current package, .. = parent package. Inside relpkg/sub/ops.py:
# relpkg/sub/ops.py — uses both relative forms: . for siblings, .. for the parent package.
"""Uses both relative forms: . for siblings, .. for the parent package."""
from ..core import shout
from . import helper
from .helper import wrap
def run() -> None:
print(wrap(shout("relative imports work")))# rel_demo.py — relative imports only work when the file is imported as part
# of its package.
from relpkg.sub import ops
ops.run()$ python3 rel_demo.py
[RELATIVE IMPORTS WORK!]
$ python3 relpkg/sub/ops.py # run the file directly instead
Traceback (most recent call last):
...
ImportError: attempted relative import with no known parent packagefrom ..core import shout walked up from relpkg.sub to relpkg and found core.py; from . import helper found the sibling helper.py. Beautiful — until you run ops.py as a script: there is no package context, so .. has nothing to mean and Python raises ImportError: attempted relative import with no known parent package.
Rules:
- Inside a package, relative imports (
from . import x,from ..core import y) are idiomatic — they survive the package being renamed or nested deeper. - In top-level scripts, always use absolute imports (or no package at all). A script run as
python3 tools/report.pyis not part oftoolsunlesstoolsis a package and you run it with-m. - If you see
attempted relative import with no known parent package, the file is being run/imported outside its package — run it withpython -m package.modulefrom the project root, or convert the import to absolute. - Absolute imports are also what you want across packages:
from triage.models import Ticketworks regardless of which file you're in, as long astriage's parent is onsys.path.
3.2 Circular imports#
The classic import bug: module a needs something from b at the top of the file, and b needs something from a at the top of its file. Whichever loads first is only half-built when the other asks for a name that does not exist yet.
# billing.py — half of a circular import: billing imports orders at the top.
"""Half of a circular import: billing imports orders at the top."""
import orders
TAX_RATE = 0.2# orders.py — other half: orders asks billing for a name defined only later.
"""Other half: orders asks billing for a name defined only later."""
from billing import TAX_RATE # billing is mid-import; TAX_RATE not defined yet
SHIPPING_FEE = 4.99# circ_run.py — trigger the circular import on purpose.
import billing
print(billing.TAX_RATE)$ python3 circ_run.py
Traceback (most recent call last):
File ".../circ_run.py", line 2, in <module>
import billing
File ".../billing.py", line 3, in <module>
import orders
File ".../orders.py", line 3, in <module>
from billing import TAX_RATE
ImportError: cannot import name 'TAX_RATE' from 'billing' (consider renaming '.../billing.py' if it has the same name as a library you intended to import)(Paths elided — yours will show your own directories. Real output on Python 3.14.)
The fixes, in order of preference:
- Break the cycle by moving shared code down. If both modules need
TAX_RATE, put it in a third module (pricing.py) that neither imports back from. Cycles almost always mean "this code wanted to live lower in the dependency graph". - Import inside the function that uses it (lazy import, 1.7) — legitimate when the dependency is genuinely optional or heavy, less good as a routine cycle-breaker because it hides the structure.
- Restructure: merge the modules, or invert the dependency (pass a callable/object in instead of importing the module).
Why does import billing alone (without from billing import TAX_RATE inside orders) sometimes not fail? Because import orders binds the module object and resolves orders.TAX_RATE later, at call time — by then billing has finished initialising. The from X import name form demands the attribute now, mid-import. That asymmetry is why circular-import bugs appear and disappear when someone "fixes" them by switching import styles.
3.3 Peeking without importing: importlib.util.find_spec and sys.modules#
Before importing, you can ask the import system where a module would come from — no code executed:
# spec_demo.py — ask the import system where a module would come from,
# without importing it. Loader names are stable across machines.
# Run this in the project folder from Parts 2-3 (the one containing relpkg/).
import importlib.util
for name in ("math", "json", "relpkg", "does_not_exist"):
spec = importlib.util.find_spec(name)
if spec is None:
print(f"{name:>16} -> NOT FOUND")
else:
print(f"{name:>16} -> {type(spec.loader).__name__}") math -> ExtensionFileLoader
json -> SourceFileLoader
relpkg -> SourceFileLoader
does_not_exist -> NOT FOUND(Run anywhere else, relpkg -> NOT FOUND — find_spec searches sys.path, so the package must actually be importable from where you run it. Swap relpkg for email or xml — guaranteed-present packages — if you want the demo to work in any folder.)
find_spec returns a module spec — where the module lives and which loader will execute it — or None. ExtensionFileLoader means compiled extension (.so on POSIX, .pyd on Windows), SourceFileLoader a .py file, BuiltinImporter something frozen into the interpreter (sys). Uses: checking a module exists before optional-import logic (if importlib.util.find_spec("pandas")), debugging "why is this json being imported" (compare spec.origin), and tooling. sys.modules (1.3) shows what is already loaded — the difference matters: find_spec consults the path, sys.modules consults the cache.
Part 4: Third-party packages and virtual environments#
Everything so far used only the standard library. Real projects need more: httpx for HTTP, pydantic for validation, pytest for tests, numpy for arrays. Those live on PyPI (the Python Package Index, pypi.org) and reach your machine through an installer — pip (which ships with Python) or uv (the faster Rust-based tool this path prefers). This part explains where packages come from, why you almost never install them "globally", and how to keep versions from fighting.
4.1 PyPI, pip and uv#
- PyPI is the public package index: every release of every package, with metadata, dependencies and release files.
pip install httpxasks PyPI forhttpx, reads its dependency list, downloads the right wheel for your platform and Python version, and unpacks it into your environment'ssite-packagesdirectory — where the import system finds it (1.3). pipis the classic installer:pip install httpx,pip install -r requirements.txt,pip list,pip show httpx,pip uninstall httpx. It works everywhere but is slow at resolving dependencies.uvdoes the same jobs faster and manages Python versions too:uv add httpx(adds topyproject.tomland installs),uv pip list,uv pip install,uv sync. This path usesuvthroughout; 01B.1 owns the full project workflow, and 03.1 §4.3 shows thepipequivalents.
4.2 Virtual environments: why they exist#
A virtual environment ("venv") is a private directory containing its own python executable, its own site-packages, and its own installed packages. Without one, pip install writes into the interpreter's shared site-packages — so project A's httpx==0.28 and project B's httpx==0.27 fight, and uninstalling for one breaks the other. Venvs make each project's dependencies independent: same interpreter, different package sets.
python3 -m venv .venv # create .venv in the current folder (adds pip via ensurepip)
python3 -m venv --without-pip .venv-lite # stdlib only, no pip bootstrap — used for this demo$ python3 -m venv --without-pip .venv-demo
$ ls .venv-demo/bin
activate
activate.csh
activate.fish
Activate.ps1
python
python3
python3.14
𝜋thon
$ .venv-demo/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)"
Truesys.prefix != sys.base_prefix is True — proof the venv's Python is a different environment from the base interpreter, not just a folder of files. (The 𝜋thon entry is new in Python 3.14's venvs — a playful symlink; ignore it.)
Activating puts the venv's bin/ (or Scripts/ on Windows) first on PATH, so bare python/pip/uv commands hit the venv's copies:
# macOS / Linux
source .venv/bin/activate # prompt changes to show (.venv)
deactivate # leave it
# Windows PowerShell
.\.venv\Scripts\Activate.ps1uv venv creates the same kind of environment (uv venv then uv pip install ..., or just uv add inside a project which does both). uv can also install standalone Pythons (uv python install 3.13), which is why this path prefers it — one tool for interpreters and packages.
4.3 requirements.txt vs pyproject.toml#
Two files describe "what this project needs"; they are not competitors but different generations:
requirements.txt pyproject.toml [project] table
----------------- ------------------------------
# a flat list of pins name = "triage"
httpx==0.28.1 version = "0.1.0"
pydantic==2.14.3 requires-python = ">=3.11"
python-dotenv==1.2.4 dependencies = [
pytest==9.2.0 "httpx>=0.28,<0.29",
-r other-requirements.txt "pydantic>=2.14",
# or unpinned: ]
httpx [project.scripts]
# or with hashes: triage = "triage.cli:main"
--require-hashes(The pins in the left column were the latest PyPI releases of those four packages as of November 2026, checked on each package's PyPI page; look up the current ones before copying them.)
requirements.txtis the old, simple contract: "install exactly these".pip install -r requirements.txtreproduces an environment. Still everywhere — deployment docs, Dockerfiles, CI — and perfectly fine for applications.pyproject.tomlis the modern standard (PEP 518/621): it declares the project itself — name, version, Python requirement, dependencies with compatible ranges, scripts, build system.uv/pipread it to create lockfiles (uv.lock,requirements.txtexports) that pin everything transitively. For libraries and serious applications it is the right home; 01B.1 owns it fully.
This lesson's toml_demo.py reads a real file with the standard library — tomllib (new in 3.11, read-only TOML parsing; the write-side lives in tomli-w, third-party). Here is the pyproject.toml it reads, saved next to the script:
# pyproject.toml
[project]
name = "triage"
version = "0.1.0"
description = "Support-ticket triage toolkit"
requires-python = ">=3.11"
dependencies = [
"httpx>=0.28,<0.29",
]
[project.scripts]
triage = "triage.cli:main"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"# toml_demo.py — read pyproject.toml with the stdlib tomllib (3.11+).
import tomllib
with open("pyproject.toml", "rb") as f: # tomllib needs bytes, not text
data = tomllib.load(f)
print("name ->", data["project"]["name"])
print("requires-py ->", data["project"]["requires-python"])
print("deps ->", data["project"]["dependencies"])
print("scripts ->", data["project"]["scripts"])
print("build backend->", data["build-system"]["build-backend"])name -> triage
requires-py -> >=3.11
deps -> ['httpx>=0.28,<0.29']
scripts -> {'triage': 'triage.cli:main'}
build backend-> hatchling.buildTwo details worth remembering: tomllib wants binary mode ("rb") — TOML is UTF-8 and the parser takes bytes; and the result is plain dicts/lists, so data["project"]["dependencies"] is just indexing.
pip list / uv pip list show what is installed in the current environment; pip show httpx shows one package's version, location and dependencies; pip install -e . (editable) installs the current project as a link so import mypkg resolves to your src/ — the mechanism behind the src/ layout in 2.3. pip freeze / uv pip freeze dumps the environment as requirements.txt-style pins — useful for "it worked here, capture it".
4.4 Versions, pinning and dependency hell#
A version spec like httpx>=0.28,<0.29 means "0.28.x but not 0.29"; == pins exactly; ~= is the compatible release operator — ~=2.14 means >=2.14, ==2.* (anything in the 2.x line from 2.14 up, so <3.0), while ~=2.14.0 tightens it to >=2.14.0, <2.15. Pinning (writing exact == versions, ideally via a lockfile) is what makes "works on my machine" reproducible: the same pip install -r gives the same code everywhere.
Dependency hell is what happens without it: package A wants httpx<0.28, package B wants httpx>=0.28, your project wants httpx==0.28.1 — the resolver either fails loudly (good) or, historically, silently produced a broken mix (bad). Modern pip/uv resolvers refuse impossible sets rather than guessing, but conflicts still surface as resolution errors you must untangle by upgrading/downgrading one of the three parties. Rules that prevent most of it:
- Pin direct dependencies; let a lockfile pin the transitive ones.
- Upgrade deliberately (
uv lock --upgrade-package httpx), neverpip install --upgradeblindly across a project. - Keep one environment per project (venv) so "latest" means something local, not global.
- Read the error: resolver failures (uv's "No solution found when resolving dependencies", pip's "Cannot install ...") name the conflicting requirements — they are documentation, not noise.
4.5 Supply-chain hygiene#
Installing a package means executing a stranger's code on your machine — at install time (setup hooks) and at run time (imports). The defences are unglamorous:
- Copy names exactly from official docs or the project's own README; typosquats live one letter away (4.1).
- Pin versions (
==) and prefer lockfiles; a version that worked yesterday cannot silently change tomorrow. - Prefer widely-used packages — download counts and dependents on PyPI are a weak-but-real signal; a package only you will ever install is a risk you carry alone.
- Review what you add:
uv pip show, the package's repo link on PyPI, andpip-audit/uvaudit tooling for known CVEs where available. - Hashes:
pip install --require-hashes -r requirements.txtverifies downloaded files against recorded SHA-256 digests — the gold standard for CI/release installs. - Private indexes and
--index-url: internal packages come from your org's index, not PyPI; never let a project's config silently point elsewhere.
12.7 owns the full treatment — typosquatting, dependency confusion, malicious wheels, model-file risks — in the security module; 11C.2 covers it in CI. The habit to build now: every package you add is code you are choosing to run — choose deliberately.
Part 5: The standard library tour#
Reference
Python's motto is "batteries included": the standard library covers files, paths, JSON, CSV, SQLite, dates, maths, hashing, compression, HTTP parsing, command lines, processes and more — all offline, all free, all versioned with the interpreter you already installed. This is a tour, not a reference: each stop gets one runnable example and a pointer to where the skill is owned in depth. Where an earlier lesson already taught a module properly (01A.2 for re/string/textwrap, 01A.5 for itertools/collections, 01A.6 for enum/dataclasses, 01A.9 for pathlib/json/csv/files), the tour is deliberately brief — the skill is knowing the module exists and what it's for.
5.1 Finding your way: sys.stdlib_module_names, dir() and help()#
The stdlib is large enough that nobody memorises it — the skill is looking things up. Three tools cover 90% of it:
# explore_demo.py — how to find out what a stdlib module contains.
import sys
print("stdlib_module_names is a set ->", type(sys.stdlib_module_names).__name__)
print("'pathlib' shipped? ->", "pathlib" in sys.stdlib_module_names)
print("'tomllib' shipped (3.11+)? ->", "tomllib" in sys.stdlib_module_names)
import math
names = [n for n in dir(math) if not n.startswith("_")]
print("dir(math) finds sqrt/isclose ->", "sqrt" in names and "isclose" in names)
print("dir(math) yields many names ->", len(names) > 50)stdlib_module_names is a set -> frozenset
'pathlib' shipped? -> True
'tomllib' shipped (3.11+)? -> True
dir(math) finds sqrt/isclose -> True
dir(math) yields many names -> True(The exact count inside dir(math) grows between releases — new functions are added every version — so the demo checks membership and size rather than printing a number that would differ on 3.11 vs 3.14.)
sys.stdlib_module_names(Python 3.10+) is the authoritative list of what ships with your interpreter — membership tests are how you check "istomllibavailable on 3.11?" without importing.dir(module)lists its public names;help(module)orhelp(module.function)in the REPL prints the docstring — the built-in documentation browser.pydocdoes the same from the shell (python3 -m pydoc json).- The official docs mirror all of it at docs.python.org/3/library/ — the "library reference" is organised exactly like this tour. 00.8 teaches how to read documentation effectively.
5.2 Files and paths: pathlib, os, sys, shutil, tempfile#
Five modules, one job family — getting around the filesystem:
pathlib— the modern, object-oriented way:Path("data") / "tickets.csv",.exists(),.is_dir(),.suffix,.stem,.parent,.with_suffix(),.read_text()/.write_text(),.mkdir(parents=True),.iterdir(),.glob()/.rglob(),.resolve(),.relative_to(). 01A.9 owns it deeply.os— the older string/path layer underneath:os.environ(environment variables),os.getcwd(),os.listdir(),os.path.join(),os.cpu_count(),os.name/os.sep(platform facts). Still needed for env vars and process facts; for paths preferpathlib.sys— interpreter facts:sys.argv(command-line arguments),sys.path(the import search path, 1.3),sys.modules(the import cache),sys.version_info,sys.executable,sys.exit().shutil— file operationspathlibdoesn't do:copy2,copytree,move,rmtree(dangerous — see the warnings in 01A.9).tempfile— throwaway files/dirs that clean themselves up:TemporaryDirectory(),NamedTemporaryFile(),mkdtemp().
# files_demo.py — pathlib, shutil and tempfile in one pass.
import shutil
import tempfile
from pathlib import Path
# --- pathlib: build a tiny tree, then ask questions about it -------------
root = Path("demo_tree")
(root / "reports" / "2026").mkdir(parents=True, exist_ok=True)
(root / "reports" / "summary.txt").write_text("Q3 revenue: up\n", encoding="utf-8")
(root / "reports" / "2026" / "jan.csv").write_text("month,amount\njan,10\n", encoding="utf-8")
print("cwd/demo_tree is_dir ->", (Path.cwd() / "demo_tree").is_dir())
print("exists ->", (root / "reports").exists())
print("is_dir ->", (root / "reports").is_dir())
print("suffix ->", (root / "reports" / "summary.txt").suffix)
print("stem ->", (root / "reports" / "2026" / "jan.csv").stem)
print("parent name ->", (root / "reports" / "summary.txt").parent.name)
print("with_suffix ->", (root / "reports" / "summary.txt").with_suffix(".md").name)
# glob/rglob: pattern matching without os.walk
print("txt files ->", sorted(p.name for p in root.rglob("*.txt")))
print("all csv ->", sorted(str(p.relative_to(root)) for p in root.rglob("*.csv")))
# read_text/write_text are the idiomatic way to do whole-file I/O
print("read back ->", (root / "reports" / "summary.txt").read_text(encoding="utf-8").strip())
# --- shutil: copy/move whole files and trees ------------------------------
shutil.copy2(root / "reports" / "summary.txt", root / "reports" / "summary-copy.txt")
print("after copy2 ->", sorted(p.name for p in (root / "reports").iterdir() if p.is_file()))
# --- tempfile: a directory that cleans itself up --------------------------
with tempfile.TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
(tmp_path / "scratch.txt").write_text("temporary", encoding="utf-8")
print("inside tempdir ->", (tmp_path / "scratch.txt").exists())
print("after with-block ->", Path(tmp).exists())
# tidy up: the demo created demo_tree/ in your working folder — remove it.
shutil.rmtree(root)
print("cleaned up ->", not root.exists())cwd/demo_tree is_dir -> True
exists -> True
is_dir -> True
suffix -> .txt
stem -> jan
parent name -> reports
with_suffix -> summary.md
txt files -> ['summary.txt']
all csv -> ['reports/2026/jan.csv']
read back -> Q3 revenue: up
after copy2 -> ['summary-copy.txt', 'summary.txt']
inside tempdir -> True
after with-block -> False
cleaned up -> True# os_demo.py — the os module: environment, paths and process facts.
import os
import sys
print("environ.get default ->", os.environ.get("TRIAGE_ENV", "dev"))
print("getcwd is a dir ->", os.path.isdir(os.getcwd()))
print("getcwd == '.' ->", os.path.samefile(os.getcwd(), "."))
print("path.join ->", os.path.join("data", "tickets.csv"))
print("sep is '/' here ->", os.sep == "/") # False on Windows
print("cpu_count >= 1 ->", os.cpu_count() >= 1)
print("argv via sys ->", sys.argv[0])environ.get default -> dev
getcwd is a dir -> True
getcwd == '.' -> True
path.join -> data/tickets.csv
sep is '/' here -> True
cpu_count >= 1 -> True
argv via sys -> os_demo.py(os.sep == "/" prints True here on macOS; on Windows it is False — that is the point of the check, not a bug.) sys.argv is covered again with argparse in 5.9; the one-line habit to build now: always encoding="utf-8" on read_text/write_text/open — the default is locale-dependent and bites on Windows (01A.9 explains).
5.3 Data formats: json, csv and sqlite3#
The three formats AI code meets daily, all in the stdlib:
# data_demo.py — json, csv and sqlite3: the three formats AI code meets daily.
import csv
import io
import json
import sqlite3
# --- json: Python objects <-> JSON text ----------------------------------
ticket = {"id": "T-1042", "subject": "Invoice PDF missing", "tags": ["billing", "urgent"], "score": 0.87}
text = json.dumps(ticket, indent=2, sort_keys=True)
print("json.dumps ->")
print(text)
print("round-trip equal ->", json.loads(text) == ticket)
# --- csv: rows of strings; DictReader maps headers to keys ----------------
csv_text = "id,subject,priority\nT-1,Printer offline,1\nT-2,VPN drops,2\n"
rows = list(csv.DictReader(io.StringIO(csv_text)))
print("csv rows ->", rows)
print("types are str ->", all(isinstance(v, str) for r in rows for v in r.values()))
# --- sqlite3: a real (in-memory) database, stdlib only --------------------
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE tickets (id TEXT PRIMARY KEY, subject TEXT, priority INTEGER)")
con.executemany("INSERT INTO tickets VALUES (?, ?, ?)",
[("T-1", "Printer offline", 1), ("T-2", "VPN drops", 2)])
for row in con.execute("SELECT id, subject FROM tickets ORDER BY priority"):
print("sqlite row ->", row)
con.close()json.dumps ->
{
"id": "T-1042",
"score": 0.87,
"subject": "Invoice PDF missing",
"tags": [
"billing",
"urgent"
]
}
round-trip equal -> True
csv rows -> [{'id': 'T-1', 'subject': 'Printer offline', 'priority': '1'}, {'id': 'T-2', 'subject': 'VPN drops', 'priority': '2'}]
types are str -> True
sqlite row -> ('T-1', 'Printer offline')
sqlite row -> ('T-2', 'VPN drops')json:dumps/loads(text ↔ objects) anddump/load(files). API responses are JSON; 03.x leans on it constantly, and 01A.9 owns the edge cases (JSONDecodeError,default=, tuples→lists).csv:reader/DictReader/writer/DictWriter. Everything arrives as a string — thetypes are str -> Trueline above is the reminder to convert deliberately. Excel-exported CSVs may carry a BOM (utf-8-sighandles it) — details in 01A.9.sqlite3: a real SQL database in a single file —:memory:for tests, a path for persistence. Parameterised queries (?placeholders) are the habit that prevents injection. 00.7 teaches SQL itself; later modules use SQLite for metadata stores, eval datasets and cache backends (11B.3 §3.4).
5.4 Time: datetime, zoneinfo, time, calendar#
LLM work is timestamp-heavy: request logs, cache TTLs, "as of" dates, rate-limit windows. The traps are naive vs aware datetimes and local vs UTC.
# time_demo.py — datetime, zoneinfo, timedelta and ISO 8601, deterministically.
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
# A fixed instant, no "now" anywhere: output is identical on every machine.
start = datetime(2026, 11, 1, 9, 30, tzinfo=timezone.utc)
deadline = start + timedelta(days=5, hours=3)
print("start (UTC) ->", start.isoformat())
print("deadline (UTC) ->", deadline.isoformat())
print("days between ->", (deadline - start).days)
# The same instant in two zones: same moment, different wall-clock reading.
# On Windows you may need `uv add tzdata` — the package ships the tz database.
kolkata = ZoneInfo("Asia/Kolkata") # UTC+5:30, no DST
ny = ZoneInfo("America/New_York")
utc_instant = datetime(2026, 11, 6, 12, 0, tzinfo=timezone.utc)
print("in Kolkata ->", utc_instant.astimezone(kolkata).strftime("%H:%M %Z"))
print("in New York ->", utc_instant.astimezone(ny).strftime("%H:%M %Z %z"))
print("same instant? ->", utc_instant == utc_instant.astimezone(kolkata))
# Parsing ISO 8601 back, and the naive/aware trap:
parsed = datetime.fromisoformat("2026-11-06T17:30:00+05:30")
print("parsed tzinfo ->", parsed.tzinfo)
naive = datetime(2026, 11, 6, 12, 0) # no tzinfo: a wall clock, not an instant
try:
_ = naive - utc_instant
except TypeError as e:
print("naive - aware ->", type(e).__name__ + ":", e)start (UTC) -> 2026-11-01T09:30:00+00:00
deadline (UTC) -> 2026-11-06T12:30:00+00:00
days between -> 5
in Kolkata -> 17:30 IST
in New York -> 07:00 EST -0500
same instant? -> True
parsed tzinfo -> UTC+05:30
naive - aware -> TypeError: can't subtract offset-naive and offset-aware datetimesThe rules that prevent the classic bugs:
- Store and transmit UTC.
datetime.now(timezone.utc)(3.11+ also has the shorterfrom datetime import UTC, thendatetime.now(UTC)),.astimezone()to display locally,isoformat()/fromisoformat()for ISO 8601 strings — the format every API uses. - Aware vs naive is a type-level distinction. A datetime with
tzinfois an instant; without, it is a wall-clock reading. Mixing them raisesTypeError— good, it forces the decision. The naivedatetime.now()is the bug farm: it silently means "local time", which differs per machine. zoneinfo.ZoneInforeads the system tz database — on Windows you may needuv add tzdata(the package ships the database).timedeltafor durations;time.time()/time.monotonic()/time.perf_counter()for timestamps and measurement (5.11);calendarfor month grids.
5.5 Collections and helpers: collections, itertools, functools#
The "upgrade kits" for everyday containers — all three were touched in earlier lessons; here is the map:
collections:Counter(frequency counts — the ticket summary uses it),defaultdict(auto-vivify keys),deque(fast append/pop at both ends — the right queue),namedtuple(lightweight records; dataclasses usually win),OrderedDict(mostly obsolete — dicts are ordered since 3.7).itertools: lazy iterator combinators —chain,islice,batched(3.12+; the demo below carries a three-line 3.11 fallback so it runs on the module's 3.11 floor),groupby(input must be sorted),product/combinations/permutations,accumulate,count,cycle,tee,takewhile,zip_longest. 01A.5 owns them.functools:cache/lru_cache(memoisation),partial(pre-fill arguments),reduce,wraps/singledispatch/total_orderinghelpers,cmp_to_key. 01A.3 and 01A.5 use them.
# coll_demo.py — collections, itertools and functools, the upgrade kits.
from collections import Counter, defaultdict, deque
from functools import cache, partial, reduce
from itertools import groupby, islice
try:
from itertools import batched # itertools.batched: Python 3.12+
except ImportError: # 3.11 fallback — same result
def batched(it, n):
it = iter(it)
while batch := tuple(islice(it, n)):
yield batch
words = "the cat sat on the mat with the cat".split()
print("Counter most_common ->", Counter(words).most_common(2))
groups = defaultdict(list)
for w in words:
groups[w[0]].append(w)
print("defaultdict keys ->", sorted(groups))
d = deque(["a", "b"], maxlen=3)
d.append("c"); d.append("d")
print("deque (maxlen=3) ->", list(d)) # 'a' and 'b' fell off the left
# itertools: lazy, memory-friendly iteration
print("islice ->", list(islice(range(10), 2, 8, 2)))
print("batched ->", list(batched(range(5), 2)))
print("groupby needs sort ->", [(k, list(g)) for k, g in groupby("aaabbc", key=lambda c: c == "a")])
# functools: memoisation and partial application
@cache
def expensive(n: int) -> int:
print(f" (computing {n})")
return n * n
print("cached calls ->", [expensive(4) for _ in range(3)])
shout = partial(print, sep=" ")
shout("partial", "application", "works")
print("reduce sum ->", reduce(lambda a, b: a + b, [1, 2, 3, 4], 0))Counter most_common -> [('the', 3), ('cat', 2)]
defaultdict keys -> ['c', 'm', 'o', 's', 't', 'w']
deque (maxlen=3) -> ['b', 'c', 'd']
islice -> [2, 4, 6]
batched -> [(0, 1), (2, 3), (4,)]
groupby needs sort -> [(True, ['a', 'a', 'a']), (False, ['b', 'b', 'c'])]
(computing 4)
cached calls -> [16, 16, 16]
partial application works
reduce sum -> 10Note expensive(4) printed "(computing 4)" once for three calls — @cache remembered the answer. groupby grouped consecutive equal keys only: the output [(True, [a,a,a]), (False, [b,b,c])] looks odd because the key function c == "a" is False for both b and c — real groupby use sorts first and groups by the value itself (01A.5 has the proper pattern).
5.6 Numbers: math, statistics, random, decimal, fractions#
math:isclose(float comparison —0.1+0.2 != 0.3butisclosesays they match),floor/ceil/trunc,gcd,log/exp/sqrt,pi/e,comb/perm. Covered in 01A.2.statistics:mean,median,stdev,quantiles— one-liners over a list of numbers.random:random(),randint,choice,sample,shuffle,uniform— alwaysrandom.seed(...)in tests/demos for reproducibility (the lesson does).decimal.Decimal: exact decimal arithmetic — money.Decimal("0.1") + Decimal("0.2") == Decimal("0.3")exactly; binary floats cannot promise that.fractions.Fraction: exact rational arithmetic —Fraction(1,3) + Fraction(1,6) == Fraction(1,2).
# num_demo.py — math, statistics, random (seeded), decimal and fractions.
import math
import random
import statistics
from decimal import Decimal
from fractions import Fraction
print("isclose(0.1+0.2, 0.3) ->", math.isclose(0.1 + 0.2, 0.3))
print("floor division neg ->", -7 // 2, "| remainder:", -7 % 2)
values = [12.5, 7.0, 9.0, 15.5]
print("mean / median ->", statistics.mean(values), statistics.median(values))
random.seed(20261106) # deterministic "randomness"
print("random choices ->", [random.randint(1, 6) for _ in range(5)])
print("random.sample ->", random.sample(["a", "b", "c", "d", "e"], 2))
# Money: Decimal, because 0.1 + 0.2 != 0.3 in binary float
price = Decimal("19.99")
total = price * 3
print("Decimal total ->", total, "| exact:", total == Decimal("59.97"))
print("float would give ->", repr(0.1 + 0.2))
print("Fraction 1/3 + 1/6 ->", Fraction(1, 3) + Fraction(1, 6))isclose(0.1+0.2, 0.3) -> True
floor division neg -> -4 | remainder: 1
mean / median -> 11.0 10.75
random choices -> [6, 1, 1, 2, 2]
random.sample -> ['a', 'c']
Decimal total -> 59.97 | exact: True
float would give -> 0.30000000000000004
Fraction 1/3 + 1/6 -> 1/2Decimal is constructed from a string (Decimal("19.99")), never from a float — Decimal(0.1) inherits the float's error. When money or exact ratios matter (invoice totals, currency conversion), reach for Decimal/Fraction; when they don't, floats plus math.isclose are fine. random.seed makes demos and tests reproducible — real secrets and tokens are a different module entirely (5.7).
5.7 Encoding, hashing and identifiers: base64, hashlib, secrets, uuid#
# enc_demo.py — base64, hashlib, uuid (deterministic uuid5) and secrets.
import base64
import hashlib
import uuid
raw = b"ticket-attachment-bytes"
print("b64 encode ->", base64.b64encode(raw).decode())
print("b64 decode ->", base64.b64decode(base64.b64encode(raw)) == raw)
print("urlsafe ->", base64.urlsafe_b64encode(b"\xfb\xff\xfe").decode())
# SHA-256 of text: the standard way to fingerprint content for cache keys.
digest = hashlib.sha256(b"the quick brown fox").hexdigest()
print("sha256 fox ->", digest)
print("sha256 len ->", len(digest), "hex chars")
# uuid5 is name-based: same name, same UUID, every machine, forever.
print("uuid5 dns ->", uuid.uuid5(uuid.NAMESPACE_DNS, "tickets.example.com"))
print("uuid5 again ->", uuid.uuid5(uuid.NAMESPACE_DNS, "tickets.example.com"))
# (uuid.uuid4() is random — a different value every run; secrets.token_*
# is the right tool for tokens and keys, shown in the lesson text.)b64 encode -> dGlja2V0LWF0dGFjaG1lbnQtYnl0ZXM=
b64 decode -> True
urlsafe -> -__-
sha256 fox -> 9ecb36561341d18eb65484e833efea61edc74b84cf5e6ae1b81c63533e25fc8f
sha256 len -> 64 hex chars
uuid5 dns -> 9ce2451f-8aec-5945-9cbf-a2f2b80cea36
uuid5 again -> 9ce2451f-8aec-5945-9cbf-a2f2b80cea36base64: bytes ↔ ASCII text — safe transport for binary in JSON/headers (urlsafe_b64encodefor URL contexts). Encoding is not encryption; anyone can decode it.hashlib: SHA-256 and friends.sha256(b"text").hexdigest()fingerprints content — the primitive behind cache keys (11B.3 §3.2), change detection in ingestion pipelines (05.9 §2.2) and deduplication. Hash canonical serialisations (json.dumps(..., sort_keys=True)), notstr(dict).uuid:uuid4()random ids;uuid5(namespace, name)deterministic ids from names — perfect for "same input → same id" without a database.secrets: cryptographically secure randomness for tokens, keys, password resets —secrets.token_hex(32),secrets.token_urlsafe(32),secrets.choice. Neverrandomfor security:randomis a deterministic PRNG — fine for shuffling a playlist, catastrophic for tokens. Example output (illustrative — your exact output will differ):secrets.token_hex(8)→3f9a1c2e7b04d8f1.hmac/hashlibkeyed hashing for pseudonymous user IDs appears throughout 03.x (03.7).
5.8 Web plumbing you can use offline: urllib.parse, urllib.request, http.server#
# web_demo.py — urllib.parse (pure computation) and urllib.request on file://.
from pathlib import Path
from urllib.parse import parse_qs, urlencode, urlsplit
from urllib.request import urlopen
url = "https://api.example.com/v1/tickets?status=open&priority=1&tag=a&tag=b"
parts = urlsplit(url)
print("scheme/netloc/path ->", parts.scheme, parts.netloc, parts.path)
print("query parsed ->", parse_qs(parts.query))
print("urlencode ->", urlencode({"q": "printer offline", "page": 2}))
# urllib.request works offline against file:// URLs — handy for tests.
with urlopen(Path(__file__).resolve().as_uri()) as resp:
first_line = resp.read().decode().splitlines()[0]
print("urlopen file:// ->", first_line.strip())scheme/netloc/path -> https api.example.com /v1/tickets
query parsed -> {'status': ['open'], 'priority': ['1'], 'tag': ['a', 'b']}
urlencode -> q=printer+offline&page=2
urlopen file:// -> # web_demo.py — urllib.parse (pure computation) and urllib.request on file://.urllib.parse: pure URL computation —urlsplit,urlunsplit,parse_qs/urlencode,quote/unquote,urljoin. You will use it to build query strings for provider APIs without hand-concatenating.urllib.request: the stdlib HTTP client —urlopenworks but has no default timeout (a hung server hangs your script forever), no connection pooling and no HTTP/2. For real HTTP usehttpx(01B.5);urllib.requestis what you reach for in a script that must stay stdlib-only — and even then passtimeout=30— or to fetch afile:///data:URL in a test.http.server:python3 -m http.server 8000serves the current directory — handy for checking static files. Awareness only here; building real endpoints is 01B.7 (FastAPI) territory. The wire-level view of HTTP is 00.5/00.6 and 03.1 Part 1.
5.9 Command lines and processes: argparse, subprocess, platform, getpass#
# cli_demo.py — argparse: a real (tiny) command-line interface.
import argparse
def main() -> None:
p = argparse.ArgumentParser(description="Summarise ticket counts.")
p.add_argument("csv_file", help="path to the tickets CSV")
p.add_argument("--format", choices=["table", "json"], default="table",
help="output format (default: table)")
p.add_argument("--min-priority", type=int, default=1,
help="only tickets at least this urgent (1-5)")
args = p.parse_args()
print(f"file={args.csv_file} format={args.format} min_priority={args.min_priority}")
if __name__ == "__main__":
main()$ COLUMNS=80 python3 cli_demo.py --help
usage: cli_demo.py [-h] [--format {table,json}] [--min-priority MIN_PRIORITY]
csv_file
Summarise ticket counts.
positional arguments:
csv_file path to the tickets CSV
options:
-h, --help show this help message and exit
--format {table,json}
output format (default: table)
--min-priority MIN_PRIORITY
only tickets at least this urgent (1-5)
$ python3 cli_demo.py tickets.csv --format json --min-priority 2
file=tickets.csv format=json min_priority=2argparse wraps --help to your terminal width — COLUMNS=80 pins it here so the output is reproducible (at wider widths the usage: line collapses onto one line; the options list is identical either way).
argparse gives you --help, type conversion (type=int), choices, defaults and error messages for free — the triage CLI in Part 7 uses it. For small internal tools typer/click (third-party) are nicer; argparse is the stdlib floor and always available. sys.argv hand-parsing is for scripts under ~5 arguments.
# proc_demo.py — subprocess without a shell, and why shell=True is dangerous.
import subprocess
import sys
# The safe pattern: pass an argv list, never a string for a shell to parse.
proc = subprocess.run(
[sys.executable, "-c", "print('hello from a child process')"],
capture_output=True, text=True, check=True,
)
print("child stdout ->", proc.stdout.strip())
print("returncode ->", proc.returncode)
# capture a non-zero exit instead of raising:
proc2 = subprocess.run([sys.executable, "-c", "import sys; sys.exit(3)"],
capture_output=True)
print("failing rc ->", proc2.returncode)
# DANGER, shown not run: subprocess.run(f"cat {name}; rm -rf /", shell=True)
# would hand the whole string to /bin/sh — metacharacters (; | && $()) become
# live syntax. Always prefer the argv list above.child stdout -> hello from a child process
returncode -> 0
failing rc -> 3subprocess.run(argv, capture_output=True, text=True) is the workhorse: argv is a list — ["git", "status"], never "git status; rm -rf /". shell=True hands the string to /bin/sh, where ;, |, &&, $(...) become live syntax — an injection hole whenever any part of the command came from outside your code. Even without shell=True, an allowlisted program can still be dangerous (cat ../../etc/passwd); real agent harnesses add path sandboxing and policy layers — 08A.15 §2.3 shows the guards a coding agent puts around exactly this call. check=True raises CalledProcessError on non-zero exit; omit it and inspect .returncode yourself.
platform.system()/platform.machine() report OS facts (output varies — check your own); getpass.getpass("API key: ") reads a secret without echoing it (interactive only — awareness); getpass.getuser() returns the login name. os.environ.get("NAME") reads environment variables — 01B.2 owns env vars and secrets properly.
5.10 Concurrency: names and purposes#
You will hear these constantly; the deep versions are 01B.3 (async) and 01B.4 (concurrency patterns). One line each:
| Module | What it is | Reach for it when |
|---|---|---|
threading |
OS threads sharing one process; in the standard build the GIL means only one thread runs Python bytecode at a time (optional free-threaded builds, officially supported since 3.14, lift that limit — 01A.1) | I/O-bound waits (network, disk) where the GIL releases — simple parallelism |
multiprocessing |
Separate processes, each with its own interpreter — true parallelism for CPU work | CPU-bound work that must use every core |
concurrent.futures |
ThreadPoolExecutor/ProcessPoolExecutor: map/submit over a pool — the friendly front-end to both of the above |
"run this function over these items, collect results" — the usual answer |
asyncio |
Cooperative multitasking on one thread via async/await and an event loop |
Many concurrent I/O operations (LLM API calls!) without thread overhead — 03.9 applies it |
queue/sched |
Thread-safe queues and timed job scheduling | Producer/consumer pipelines, periodic tasks |
# futures_demo.py — concurrent.futures: threads for I/O-ish work, one line of change for processes.
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def square(n: int) -> int:
return n * n
if __name__ == "__main__": # ProcessPoolExecutor needs this guard on some platforms
work = [1, 2, 3, 4, 5]
with ThreadPoolExecutor(max_workers=3) as pool:
print("threads ->", list(pool.map(square, work)))
with ProcessPoolExecutor(max_workers=2) as pool:
print("processes ->", list(pool.map(square, work)))threads -> [1, 4, 9, 16, 25]
processes -> [1, 4, 9, 16, 25]Python 3.14 added a third pool, InterpreterPoolExecutor (with the concurrent.interpreters module, PEP 734): several isolated interpreters inside one process, each with its own GIL, as a lighter-weight middle path between threads and processes. It is new and its trade-offs are still settling, so treat it as awareness for now.
Same results, different machinery: swap ThreadPoolExecutor for ProcessPoolExecutor and the work moves to separate interpreters — which is why ProcessPoolExecutor needs the if __name__ == "__main__" guard (child processes re-import your file). For I/O-bound LLM calls, threads or asyncio suffice; CPU-bound batch embedding is where processes earn their keep (01B.4 decides properly).
5.11 The long tail: config, archives, warnings, pprint, html and friends#
The remaining modules worth knowing by name, each with a runnable example where it earns one:
# misc1_demo.py — configparser, tomllib, warnings and pprint.
import configparser
import io
import tomllib
import warnings
from pprint import pprint
# --- configparser: INI files ------------------------------------------------
ini = """
[DEFAULT]
model = gpt-6-luna
retries = 3
[production]
timeout = 30
"""
cfg = configparser.ConfigParser()
cfg.read_file(io.StringIO(ini))
print("ini section ->", cfg.sections())
print("ini value ->", cfg.get("production", "timeout"))
print("ini default ->", cfg.get("production", "model")) # inherited from [DEFAULT]
print("fallback ->", cfg.get("staging", "model", fallback="(unset)"))
# --- tomllib: read TOML (pyproject.toml) — read-only, stdlib since 3.11 -----
pyproject = b"""
[project]
name = "triage"
version = "0.1.0"
dependencies = ["httpx"]
"""
data = tomllib.loads(pyproject.decode())
print("toml name ->", data["project"]["name"])
print("toml deps ->", data["project"]["dependencies"])
# --- warnings: catch them programmatically for a deterministic demo ---------
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
warnings.warn("this API will be renamed next release", DeprecationWarning)
print("warning caught->", str(caught[0].message))
# --- pprint: readable dumps of nested data ----------------------------------
nested = {"tickets": [{"id": f"T-{i}", "tags": ["a", "b"], "meta": {"x": 1}} for i in range(2)]}
pprint(nested, width=60)ini section -> ['production']
ini value -> 30
ini default -> gpt-6-luna
fallback -> (unset)
toml name -> triage
toml deps -> ['httpx']
warning caught-> this API will be renamed next release
{'tickets': [{'id': 'T-0',
'meta': {'x': 1},
'tags': ['a', 'b']},
{'id': 'T-1',
'meta': {'x': 1},
'tags': ['a', 'b']}]}configparser: INI files ([section]+key = value) — classic.ini/.cfgconfig. Only the uppercase[DEFAULT]section is special: its keys are inherited by every other section (cfg.get("production", "model")foundmodeleven though[production]never set it), andcfg.sections()does not list it. A section merely nameddefault(lowercase) is ordinary, not special.fallback=covers the genuinely-missing case — here thestagingsection does not exist at all, socfg.get("staging", "model", fallback="(unset)")returns the fallback instead of raisingNoSectionError.tomllib: read-only TOML (3.11+) —pyproject.toml,uv.toml, tool configs. Pairs withos.environ/pydantic-settingsin 01B.2.warnings:warnings.warn(msg, DeprecationWarning)for "still works but going away" — Python's own deprecation channel.catch_warnings(record=True)intercepts them (tests use this);-W errorturns them into exceptions.pprint: pretty-print nested structures readably — debugging dicts/lists thatprintdumps as one long line.
# misc2_demo.py — gzip, zipfile, html and xml.etree.ElementTree.
import gzip
import io
import zipfile
import zlib
from html import escape
from xml.etree import ElementTree as ET
payload = "ticket export: 42 rows\n".encode()
# --- gzip / zlib: compress bytes ---------------------------------------------
packed = gzip.compress(payload, mtime=0) # mtime=0 -> reproducible bytes
print("gzip roundtrip ->", gzip.decompress(packed) == payload)
print("zlib roundtrip ->", zlib.decompress(zlib.compress(payload)) == payload)
# --- zipfile: a real .zip in memory -------------------------------------------
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
info = zipfile.ZipInfo("tickets.csv", date_time=(2026, 11, 6, 12, 0, 0))
zf.writestr(info, b"id,subject\nT-1,Printer\n")
buf.seek(0)
with zipfile.ZipFile(buf) as zf:
print("zip names ->", zf.namelist())
print("zip content ->", zf.read("tickets.csv").decode().splitlines()[0])
# --- html: escape user text before putting it in a page ------------------------
user_text = '<script>alert("x")</script> & friends'
print("html.escape ->", escape(user_text))
# --- xml.etree: parse XML without third-party libraries ------------------------
doc = ET.fromstring("<tickets><ticket id='T-1'>Printer</ticket></tickets>")
print("xml find ->", doc.find("ticket").get("id"), doc.find("ticket").text)gzip roundtrip -> True
zlib roundtrip -> True
zip names -> ['tickets.csv']
zip content -> id,subject
html.escape -> <script>alert("x")</script> & friends
xml find -> T-1 Printergzip/zlib: DEFLATE compression for bytes/streams —.gzfiles, compressed HTTP bodies, cache payloads.bz2/lzmaare the heavier siblings.zipfile/tarfile: archives —zf.namelist(),zf.read(name); tar addsw:gzmodes. Ingestion pipelines unpack user uploads with these (05.1 parses Office/PDF archives).tarfilegets its own demo since tarballs are the other archive you will meet constantly (.tar.gzrelease bundles, model-weight archives):
# tar_demo.py — tarfile: pack and read a .tar.gz entirely in memory.
import io
import tarfile
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tf:
data = b"id,subject\nT-1,Printer\n"
info = tarfile.TarInfo("tickets.csv")
info.size = len(data)
tf.addfile(info, io.BytesIO(data))
buf.seek(0)
with tarfile.open(fileobj=buf, mode="r:gz") as tf:
print("tar names ->", tf.getnames())
print("tar read ->", tf.extractfile("tickets.csv").read().decode().splitlines()[0])tar names -> ['tickets.csv']
tar read -> id,subjecthtml:escape()/unescape()— mandatory before putting untrusted text into HTML (stored-XSS defence, 12.x).xml.etree.ElementTree: parse XML (ET.fromstring,.find,.findall,.iter) — feeds, sitemaps, SOAP-ish APIs. For HTML use a real parser, not regex or this (01A.2 makes the same point forre).
# misc3_demo.py — abc, contextlib.contextmanager and tracing a block.
from abc import ABC, abstractmethod
from contextlib import contextmanager
# --- abc: formal interfaces ---------------------------------------------------
class Reporter(ABC):
@abstractmethod
def report(self, rows: list[str]) -> str: ...
class CountReporter(Reporter):
def report(self, rows: list[str]) -> str:
return f"{len(rows)} rows"
# --- contextlib: a context manager without writing a class --------------------
@contextmanager
def traced(label: str):
print(f"{label}: enter")
try:
yield
finally:
print(f"{label}: exit") # runs even if the body raises
with traced("demo work"):
sum(i * i for i in range(10))
r = CountReporter()
print("abc report ->", r.report(["a", "b", "c"]))demo work: enter
demo work: exit
abc report -> 3 rowsabc:ABC+@abstractmethod— formal interfaces ("must implementreport"). Python's duck typing means you rarely need it; use it when a contract must be enforced or documented (01A.6 coversProtocol, the lighter modern alternative).contextlib:@contextmanagerturns a generator into awith-able object — timers, locks, suppress (contextlib.suppress(FileNotFoundError)).ExitStack,closing,redirect_stdoutround out the toolkit; 01A.8 owns context managers properly.logging: preview below; 01A.8 owns it fully, 01B.10 applies it, 11A.1 takes it to observability.
# logging_demo.py — the logging module, minimal config, no timestamps.
import logging
# One-time setup: where messages go and how they look. Real apps configure
# this once at startup; 01A.8 and 01B.10 go deep.
logging.basicConfig(
level=logging.INFO,
format="%(levelname)-7s %(name)s: %(message)s",
)
log = logging.getLogger("triage") # convention: getLogger(__name__)
log.debug("hidden: level is INFO")
log.info("loaded 8 tickets")
log.warning("skipped row 3: missing id")
try:
int("not-a-number")
except ValueError as e:
# %-style args are logged lazily (only formatted if the level is emitted);
# logger.exception(...) inside except adds a traceback — 01A.8 covers that.
log.error("failed to parse priority: %s", e)INFO triage: loaded 8 tickets
WARNING triage: skipped row 3: missing id
ERROR triage: failed to parse priority: invalid literal for int() with base 10: 'not-a-number'(The demo ran with 2>&1 because logging writes to stderr by default.) log.debug was suppressed — INFO is the floor. getLogger(__name__) gives each module its own named logger so filters/handlers can target it; logger.exception(...) inside except attaches the traceback. Never print for diagnostics in real code — print is for program output, logging is for operational events (01A.8 makes the case).
textwrap/string/re: taught in 01A.2; reminder-sized demo:
# text_demo.py — re, string and textwrap in one small pass.
# (01A.2 taught these properly; this is the tour-sized reminder.)
import re
import string
from textwrap import fill, shorten
m = re.search(r"invoice (\d+)", "please check invoice 1042 for details")
print("re groups ->", m.group(1) if m else None)
print("re findall->", re.findall(r"\d+", "a1b22c333"))
t = string.Template("Dear $name, your ticket $tid is $status.")
print("Template ->", t.substitute(name="Ada", tid="T-1", status="open"))
print("fill ->")
print(fill("the quick brown fox jumps over the lazy dog", width=30))
print("shorten ->", shorten("a very long error message that keeps going", width=30, placeholder="..."))re groups -> 1042
re findall-> ['1', '22', '333']
Template -> Dear Ada, your ticket T-1 is open.
fill ->
the quick brown fox jumps over
the lazy dog
shorten -> a very long error message...unittest:python3 -m unittest discoverrunstest_*.pyfiles;unittest.TestCase+assertEqual. Awareness here — 01A.8 previews testing, 01B.8 owns pytest (the path's test framework). Real run (illustrative — the elapsed time varies):Ran 2 tests ... OK.time/timeit:time.time()(wall clock, can jump),time.monotonic()(never jumps backwards — durations),time.perf_counter()(highest-resolution duration),timeit.timeit(stmt, number=N)for micro-benchmarks. Timings vary per machine — measure before optimising (01A.10 covers performance sense).locale: OS locale awareness (locale.getpreferredencoding()) — mostly legacy; UTF-8 is the default assumption now. Awareness only.enum/dataclasses/typing: taught in 01A.6 and 01A.10 — they are stdlib modules too (enum,dataclasses,typing,collections.abc).pickle: serialises arbitrary Python objects — neverpickle.loadsuntrusted data (it executes code). Usejsonfor data interchange; pickle only for trusted local caches you fully control (12.7 explains the risk).
Part 6: Stdlib vs third-party — choosing#
Deep-dive
The tour covered ~40 modules; the honest question is "when is the standard library enough, and when do I add a dependency?" There is no law — but these are the trade-offs that decide it in practice:
| Factor | Standard library | Third-party package |
|---|---|---|
| Install | Already there — zero dependencies, works offline | uv add/pip install, network + version resolution |
| API stability | Very stable; deprecations are rare and announced for years | Varies wildly: 0.x packages break minors; even 1.x/2.x majors break |
| Performance | Often C-backed and fast (sqlite3, hashlib, json); pure-Python parts (urllib, zipfile edge cases) are slower than optimised libs |
Specialised libs beat stdlib on their turf (orjson vs json, polars/pandas vs hand-rolled, httpx vs urllib) |
| Ecosystem fit | Universal — every Python has it | May pin you to an ecosystem (Django ORM → Django) |
| Maintenance | CPython core team; security fixes ride your Python upgrades | Depends on maintainers; abandoned packages are a real risk |
| Supply-chain surface | None beyond Python itself | Every package is code you chose to run (4.5) |
| When it wins | The default. If the stdlib does the job clearly, take it | When the stdlib genuinely can't: HTTP client pools/timeouts (httpx), validation (pydantic), test framework (pytest), arrays/dataframes (numpy/pandas), TOML writing (tomli-w), YAML (pyyaml) |
Decision rules that hold up:
- Default to stdlib.
json,csv,sqlite3,pathlib,argparse,hashlib,zoneinfocover most plumbing needs with zero cost. - Add a package when the stdlib's gap is real, not aesthetic. "
requestsis nicer thanurllib" is taste; "I need HTTP/2, connection pooling and per-request timeouts" is a gap (httpx). - Check the dependency's own dependencies.
uv addshows the tree; a one-function need that pulls 40 packages is worth re-examining. - Pin and review (4.4, 4.5) — every dependency is a maintenance and security commitment.
- When two packages do the same job, pick the one the rest of the path/ecosystem already uses — consistency beats marginal features (the path standardises on
httpx,pydantic,pytest,tenacity,numpy,pandas— see the version table in the shared brief and 01B.1).
Part 7: The triage package — putting it together#
Deep-dive
Everything in this lesson converges here: the ticket-triage toolkit from 01A.2–01A.9 becomes a real package with modules, an __init__.py, a __main__.py, an argparse CLI and python -m triage. Layout (flat, deliberately — it runs from its own folder; src/ is for installed projects, 2.3):
triage-project/
├── tickets.csv # the input data (below)
└── triage/ # the package
├── __init__.py
├── __main__.py
├── models.py
├── rules.py
├── io.py
└── cli.pytickets.csv:
id,subject,body,customer,priority
T-1001,"Invoice PDF missing from confirmation email","Customer says the invoice attachment did not arrive with the receipt",acme,2
T-1002,"Cannot log in after password reset","Login fails with 'invalid credentials' since yesterday",globex,1
T-1003,"Where is my package?","Tracking number shows no movement for 6 days",initech,2
T-1004,"Refund for duplicate charge","We were charged twice for March subscription",umbrella,1
T-1005,"App crashes on export button","Clicking export closes the app on Android 15",wayne,3
T-1006,"Change account email address","Need to move billing contact to new address",stark,2
T-1007,"How do I enable two-factor?","Security settings page does not show 2FA option",oscorp,3
T-1008,"Delivery arrived damaged","Box was crushed, contents broken",wayne,2triage/__init__.py — the front door (2.1):
# triage/__init__.py — the triage package: support-ticket triage, standard library only.
"""The triage package: support-ticket triage, standard library only.
Run it as a module: python3 -m triage tickets.csv
"""
__version__ = "0.1.0"
from triage.models import Ticket # noqa: F401 (re-exported)
from triage.rules import classify, priority_of # noqa: F401
__all__ = ["Ticket", "classify", "priority_of", "__version__"]triage/models.py — the data shape (dataclass from 01A.6):
# triage/models.py — data shapes for the triage toolkit: a Ticket record and its categories.
"""Data shapes for the triage toolkit: a Ticket record and its categories."""
from dataclasses import dataclass, field
CATEGORIES = ("billing", "shipping", "account", "bug", "other")
@dataclass
class Ticket:
ticket_id: str
subject: str
body: str = ""
customer: str = "unknown"
category: str = "other"
priority: int = 3
tags: list[str] = field(default_factory=list)triage/rules.py — classification logic, no AI, no network:
# triage/rules.py — rule-based classification: keyword matching, no AI, no network.
"""Rule-based classification: keyword matching, no AI, no network."""
from triage.models import Ticket
_KEYWORDS = {
"billing": ("invoice", "payment", "refund", "charge", "billing", "receipt"),
"shipping": ("delivery", "shipment", "tracking", "package", "arrived", "courier"),
"account": ("password", "login", "account", "email change", "2fa", "locked"),
"bug": ("error", "crash", "broken", "bug", "not working", "fails"),
}
def classify(ticket: Ticket) -> str:
"""Return the first category whose keywords appear in the ticket text."""
text = f"{ticket.subject} {ticket.body}".lower()
for category, words in _KEYWORDS.items():
if any(word in text for word in words):
return category
return "other"
def priority_of(ticket: Ticket) -> int:
"""Clamp the stored priority hint into the 1-5 scale."""
return max(1, min(5, ticket.priority))triage/io.py — input/output (01A.9 owns these formats deeply):
# triage/io.py — input and output for the triage toolkit: CSV in, JSON/CSV reports out.
"""Input and output for the triage toolkit: CSV in, JSON/CSV reports out."""
import csv
import json
from pathlib import Path
from triage.models import Ticket
def load_tickets(csv_path: str | Path) -> list[Ticket]:
"""Read tickets.csv into Ticket records. Everything in a CSV is a string."""
tickets = []
with open(csv_path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
tickets.append(Ticket(
ticket_id=row["id"],
subject=row["subject"],
body=row.get("body", ""),
customer=row.get("customer", "unknown"),
priority=int(row.get("priority", "3")),
))
return tickets
def summarise(tickets: list[Ticket]) -> dict:
"""Counts per category and the highest-priority ticket ids."""
from collections import Counter
counts = Counter(t.category for t in tickets)
urgent = sorted(tickets, key=lambda t: (-t.priority, t.ticket_id))[:3]
return {
"total": len(tickets),
"by_category": dict(sorted(counts.items())),
"top_priority": [{"id": t.ticket_id, "priority": t.priority} for t in urgent],
}
def write_json_report(summary: dict, out_path: str | Path) -> None:
Path(out_path).write_text(
json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)triage/cli.py — the argparse front end (5.9):
# triage/cli.py — command-line front end for the triage package.
"""Command-line front end for the triage package."""
import argparse
import sys
from triage.io import load_tickets, summarise, write_json_report
from triage.rules import classify, priority_of
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(
prog="triage",
description="Classify support tickets and print a summary.",
)
p.add_argument("csv_file", help="path to tickets.csv")
p.add_argument("--format", choices=["table", "json"], default="table",
help="summary format (default: table)")
p.add_argument("--out", help="also write the JSON summary to this path")
args = p.parse_args(argv)
tickets = load_tickets(args.csv_file)
for t in tickets:
t.category = classify(t)
t.priority = priority_of(t)
summary = summarise(tickets)
if args.format == "json":
import json
print(json.dumps(summary, indent=2, sort_keys=True))
else:
print(f"{'id':<8} {'category':<9} {'pri':<3} subject")
for t in sorted(tickets, key=lambda t: (-t.priority, t.ticket_id)):
print(f"{t.ticket_id:<8} {t.category:<9} {t.priority:<3} {t.subject}")
print(f"\ntotal: {summary['total']} by category: {summary['by_category']}")
if args.out:
write_json_report(summary, args.out)
print(f"report written -> {args.out}", file=sys.stderr)
return 0triage/__main__.py — makes python -m triage work (2.5):
# triage/__main__.py — makes `python3 -m triage` work: run the package's CLI.
"""Makes `python3 -m triage` work: run the package's CLI."""
from triage.cli import main
main()Run it from the project folder — real output:
$ python3 -m triage tickets.csv
id category pri subject
T-1005 bug 3 App crashes on export button
T-1007 account 3 How do I enable two-factor?
T-1001 billing 2 Invoice PDF missing from confirmation email
T-1003 shipping 2 Where is my package?
T-1006 billing 2 Change account email address
T-1008 shipping 2 Delivery arrived damaged
T-1002 account 1 Cannot log in after password reset
T-1004 billing 1 Refund for duplicate charge
total: 8 by category: {'account': 2, 'billing': 3, 'bug': 1, 'shipping': 2}
$ python3 -m triage tickets.csv --format json
{
"by_category": {
"account": 2,
"billing": 3,
"bug": 1,
"shipping": 2
},
"top_priority": [
{
"id": "T-1005",
"priority": 3
},
{
"id": "T-1007",
"priority": 3
},
{
"id": "T-1001",
"priority": 2
}
],
"total": 8
}Notice the classifications are not always the "obvious" one: T-1006 "Change account email address" lands in billing (its body mentions the billing contact) and T-1008 "Delivery arrived damaged" lands in shipping (its body's "delivery"/"arrived" beat the "broken" bug keyword). classify returns the first matching category in _KEYWORDS order — billing → shipping → account → bug — so keyword order is a design decision, and this is exactly why rule-based triage is a baseline, not a classifier.
What just happened, mapped to this lesson's machinery: python -m triage found the package on sys.path, ran __main__.py as __main__, which imported cli.main; cli imported io and rules; rules imported models; __init__.py re-exported the public names — every import form from Part 1, a package from Part 2, argparse/csv/json/pathlib/Counter from the Part 5 tour. The declared [project.scripts] triage = "triage.cli:main" in a pyproject.toml (like the one read in 4.3) would turn this into an installed triage command — that packaging step is 01B.1.
Common mistakes and real tracebacks#
Failures you will actually meet, with the real errors:
1. ModuleNotFoundError — wrong directory or wrong interpreter.
$ python3 report.py
Traceback (most recent call last):
File "report.py", line 3, in <module>
import triage
ModuleNotFoundError: No module named 'triage'You ran from the wrong folder, or triage/ is not next to the script / not installed. Fix: cd to the project root (the folder containing triage/), or install the package (pip install -e . in a src/ project). If it "worked yesterday", check sys.path[0] (1.3) — the script's directory is what matters, not the shell's pwd when using an IDE run button.
2. ImportError: cannot import name ... — circular import or renamed export.
ImportError: cannot import name 'TAX_RATE' from 'billing' (consider renaming '.../billing.py' if it has the same name as a library you intended to import)Two causes share this message: a circular import (3.2 — read the middle traceback frames for the loop) or the name simply not existing (typo, or the module defines it under __all__/underscore). On 3.13+ the "consider renaming" suffix can be a red herring for project-internal cycles.
3. ImportError: attempted relative import with no known parent package.
$ python3 relpkg/sub/ops.py
File ".../relpkg/sub/ops.py", line 3, in <module>
from ..core import shout
ImportError: attempted relative import with no known parent packageYou ran a package-internal file as a script (3.1). Run python3 -m relpkg.sub.ops from the project root instead.
4. The stdlib shadow. A local json.py/random.py/email.py silently replaces the real module (2.4) — the giveaway is weird AttributeErrors far from the cause. importlib.util.find_spec("json").origin (3.3) shows which file won.
5. The wrong environment. pip install httpx succeeds, then python script.py says ModuleNotFoundError: No module named 'httpx' — you installed into the global interpreter but run the project venv's Python (or the reverse). python -c "import sys; print(sys.executable)" vs pip show httpx | grep Location must agree (4.2).
6. SyntaxError/IndentationError on import of a file that "looks fine". Usually a stray invisible character, a missing colon, or — the sneaky one — a file saved as module.py with a trailing space or .py.txt on Windows (extensions hidden). python3 -c "import py_compile; py_compile.compile('module.py', doraise=True)" pinpoints it.
7. The global install that poisons every project. Months ago you ran pip install somepackage "just for a quick script" — no venv — and it landed in the shared interpreter's site-packages. Now a different project imports that package by accident, or its pinned version fights yours, and the error appears in a codebase that never asked for it. There is no per-project record of what you installed, so pip uninstall is guesswork. The fix is the habit from 4.2: one venv per project, and if the global site-packages is already polluted, list it (pip list) and clean out what does not belong.
Common misconceptions#
| Misconception | Reality |
|---|---|
"A module needs registration/a class/__all__ to be importable." |
A .py file is a module; __all__ only affects import *. |
"import x twice runs the file twice." |
It runs once; sys.modules caches it (1.4). |
"import * is fine if the module has __all__." |
__all__ limits the names but still dumps them unqualified into your namespace — avoid it in kept code (1.5). |
| "Relative imports are always better." | Only inside packages; scripts run by path have no package context (3.1). |
| "The 'consider renaming' ImportError means shadowing." | On 3.13+ it can also mean a circular import — read the traceback loop (3.2). |
"__init__.py is required for a package." |
Namespace packages (3.3+) work without it — but always write one anyway (2.2). |
| "Installing a package globally is fine for a quick script." | It pollutes every project and breaks the next one; venv per project, always (4.2). |
"requirements.txt and pyproject.toml do the same job." |
One pins an environment; the other declares the project. Modern projects use pyproject.toml + lockfile (4.3). |
| "The standard library is too limited for real work." | It covers files, JSON, CSV, SQLite, dates, hashing, compression, URLs, CLIs and processes — reach for third-party only when the gap is real (Part 6). |
"random is fine for tokens/keys." |
random is deterministic PRNG — use secrets (5.7). |
"subprocess.run('git status', shell=True) is normal." |
shell=True + string commands is an injection hole; pass an argv list (5.9). |
"A naive datetime.now() is 'just a timestamp'." |
It is a wall-clock reading, not an instant — store UTC-aware datetimes (5.4). |
Key takeaways#
- A module is a file; a package is a folder with
__init__.py.importruns the file once and caches it insys.modules; the search order is script dir →PYTHONPATH→ stdlib → site-packages, first hit wins. if __name__ == "__main__"separates "run me" from "import me";python -m packageruns__main__.pywith the package properly onsys.path.__init__.pyis the package's front door — keep it light, re-export the public API, set__all__.- Never name files after stdlib/third-party modules (
json.py,random.py) — silent shadowing, weird errors far from the cause. - Circular imports mean "this code wanted to live lower in the graph" — move shared code to a third module; on 3.13+ the error wording can mislead.
- One venv per project,
pyproject.toml+ lockfile for real projects, pin versions, and treat every installed package as code you chose to run. - The standard library covers most plumbing —
pathlib,json,csv,sqlite3,datetime/zoneinfo,hashlib,secrets,argparse,subprocess,urllib.parse,logging,tomllib. Learn to look modules up (dir,help,sys.stdlib_module_names, docs.python.org) rather than memorise them. - The
triagepackage proves it end-to-end:python -m triage tickets.csv— models, rules, io, cli — pure stdlib, deterministic.
Where you'll use this in the AI path#
- 01B.1 Project setup with uv — the
src/layout,pyproject.toml, lockfiles and editable installs this lesson previewed, applied to every later module's project. - 01B.2 Environment variables, configuration and secrets —
os.environ,.env,pydantic-settingsandtomllibconfig, building on 5.11. - 01B.3 Async/await and 01B.4 Concurrency — the
asyncio/concurrent.futuresnames from 5.10 become the tools for concurrent LLM calls (03.9). - 01B.10 Logging, debugging and packaging — the
loggingpreview from 5.11 and the packaging mechanics from Part 2/4, in production form. - 11B.3 Caching strategies §3.2 —
hashlibdigests of canonical JSON as cache keys, exactly the 5.7 primitive; also 05.9 §2.2 for change detection. - 08A.15 Coding agents §2.3 — the guarded
subprocesspattern from 5.9 inside a real agent harness. - 12.7 Securing data and the supply chain §5 — the supply-chain hygiene of 4.5 in full: typosquats, dependency confusion, malicious wheels.
- 00.7 SQL basics and 00.8 Reading API docs —
sqlite3from 5.3 applied to real queries, and the doc-reading skill for the library reference used in 5.1.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Module | A .py file; its filename is its import name. Top-level names become attributes. |
| Package | A directory of modules marked by __init__.py (or a namespace package without one). |
__init__.py |
The package's front door: runs once on first import; re-exports the public API. |
sys.path |
Ordered list of directories the import system searches, first hit wins. |
sys.modules |
The in-memory cache of already-imported modules — why imports run once per process. |
__pycache__ / .pyc |
The on-disk bytecode cache: compiled .pyc files (tagged per interpreter version) reused while the source's timestamp and size match. |
PYTHONPATH |
Environment variable adding directories to sys.path. |
if __name__ == "__main__" |
Guard so a file runs as script but not when imported; __main__ is the script's module name. |
python -m |
Run a module/package as __main__; python -m pkg executes pkg/__main__.py. |
__main__.py |
A package's runnable entry point for python -m package. |
| Namespace package | A package directory without __init__.py (PEP 420, Python 3.3+). |
__all__ |
Module's declared public names; controls from x import *. |
importlib.reload |
Re-execute a module file into the same module object (development tool). |
importlib.util.find_spec |
Ask where a module would load from without importing it. |
| Virtual environment (venv) | Private directory with its own Python, site-packages and installed packages. |
| PyPI | The Python Package Index — public repository of third-party packages. |
requirements.txt |
Flat pin list for reproducing an environment (pip install -r). |
pyproject.toml |
Modern project metadata file (PEP 621): name, version, deps, scripts, build system. |
| Lockfile | Generated file pinning all resolved dependencies transitively (uv.lock). |
Editable install (pip install -e .) |
Installs the project as a link to the source tree — live edits. |
| Dependency hell | Unsatisfiable/conflicting version requirements between packages. |
| Typosquatting | Malicious packages parked on misspellings of popular names. |
src/ layout |
Project layout keeping source under src/ so only installed packages import — prevents accidental imports. |
sys.stdlib_module_names |
The authoritative set of standard-library module names (3.10+). |
| Aware vs naive datetime | Datetime with tzinfo (an instant) vs without (a wall-clock reading). |
zoneinfo |
Stdlib timezone database access (ZoneInfo("Asia/Kolkata")). |
argparse |
Stdlib CLI argument parser: positionals, flags, choices, --help. |
subprocess |
Run child processes; argv-list form is safe, shell=True is dangerous. |
hashlib |
Cryptographic hash functions (SHA-256...) for fingerprints/cache keys. |
secrets |
Cryptographically secure random for tokens/keys — never random. |
uuid5 |
Deterministic UUID derived from a namespace + name. |
tomllib |
Stdlib read-only TOML parser (3.11+). |
unittest |
Stdlib test framework; awareness here, pytest owns testing later. |
All terms are also collected in the glossary.
Exercises#
- Two import forms (1.2): create
slug.pywith aslugify(text)function (lowercase, non-alphanumerics →-, strip-). Import it once asimport slugand once asfrom slug import slugify, and print both results for"Invoice PDF Missing!"and"Where is my package?". __all__in action (1.5): in a module define__all__ = ["a"], functionsa()andb(). What doesfrom mod import *bind, and what happens when you callb()?- Search-path order (1.3): put a
who.pyprintingANSWER = "x"indirA/andANSWER = "y"indirB/. Predict, then verify withPYTHONPATH, which wins from a neutral directory and which wins when youcd dirBfirst. - Circular import fix (3.2):
billing.pydoesimport ordersthen definesTAX_RATE;orders.pydoesfrom billing import TAX_RATE. Restructure so the cycle disappears — put the shared constant in a third module. Show it working. python -m(2.5): add__main__.pyto a two-module package sopython3 -m pkgprints a greeting using a relative import. Explain whypython3 pkg/__main__.pyfails.- venv reasoning (4.2): you ran
pip install httpxandpython -c "import httpx"still fails. List the three checks that find the mismatch — no installs needed. - requirements vs pyproject (4.3–4.4): write a
requirements.txtpinninghttpx==0.28.1,pydantic==2.14.3,pytest==9.2.0, then explain what apyproject.toml+ lockfile would add. - Cache key (5.7): hash a request dict
{"model": "gpt-6-luna", "messages": [{"role": "user", "content": "hi"}], "max_output_tokens": 200}withhashlib.sha256(json.dumps(req, sort_keys=True, separators=(",", ":")).encode()).hexdigest()[:16]. Changemax_output_tokensto400— does the key change? Why issort_keys=Trueessential? - argparse (5.9): extend
cli_demo.pywith a--dry-runflag that prints the parsed args and exits0without doing work. Run--help. - subprocess safety (5.9): rewrite
subprocess.run(f"cat {filename}", shell=True)as a safe argv-list call, and name two inputs that would have been dangerous undershell=True. - datetime (5.4): parse
"2026-11-01T09:30:00+00:00"withfromisoformat, addtimedelta(hours=72), print the ISO result. Then explain what breaks if you subtract a naivedatetime(2026,11,4,12,0)from it. - Stdlib or package? (Part 6): for each need — parse JSON, validate a Pydantic-shaped payload, make an HTTP/2 request with pooling, read a YAML file, hash a file for change detection — say stdlib or third-party and name the module/library.
tomllib(5.11/4.3): read a small TOML string withtomllib.loads, print one nested value. Remember it needsstr/bytes, not a text-mode file handle forload.- Package design (Part 2/7): the
triagepackage putsclassifyinrules.py,Ticketinmodels.py, CSV/JSON inio.py, CLI incli.py. Justify each placement in one sentence, and say what would break ifclassifylived incli.pyinstead. - Import debugging (3.3): a script says
ModuleNotFoundError: No module named 'requests'though you "installed it". Write the two commands that reveal which environmentpythonandpipare actually using.
Solutions
slugifyusesre+unicodedata(both stdlib). Ran for real:
$ python3 ex1.py
invoice-pdf-missing
where-is-my-package# slug.py
import re
import unicodedata
def slugify(text: str) -> str:
text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", text.lower())).strip("-")-
__all__ = ["a"]means onlyais bound;braisesNameErroreven though it exists in the module — verified withstar2demo.py(a() -> A,b() -> NameError, 1.5). -
From a neutral directory the first
PYTHONPATHentry wins;cd dirBputs the cwd first onsys.path, sodirBwins regardless — verified in 1.3 (PYTHONPATH=patha:pathb→first, reversed →second,cd pathb→second). -
Move
TAX_RATEintopricing.py; bothbilling.pyandorders.pyimport frompricing, which imports nothing back, so the cycle cannot form.python # pricing.py TAX_RATE = 0.2python # billing.py from pricing import TAX_RATE def total(net: float) -> float: return round(net * (1 + TAX_RATE), 2)python # orders.py from pricing import TAX_RATE SHIPPING_FEE = 4.99 def order_total(net: float) -> float: return round(net * (1 + TAX_RATE) + SHIPPING_FEE, 2)python # run.py import billing import orders print("billing.total(100) ->", billing.total(100)) print("orders.order_total(100) ->", orders.order_total(100))Output billing.total(100) -> 120.0 orders.order_total(100) -> 124.99 -
Layout:
pkg/__init__.py(empty),pkg/util.pyandpkg/__main__.py.python # pkg/util.py def shout(text: str) -> str: return text.upper() + "!"python # pkg/__main__.py from .util import shout print(shout("run me"))console $ python3 -m pkg RUN ME! $ python3 pkg/__main__.py ImportError: attempted relative import with no known parent packageRun by path, the file is a top-level script:
pkg/itself lands onsys.path,__main__.pyis not part of any package, and thefrom .util importhas no parent package to be relative to. With-m, Python importspkgproperly first. -
python -c "import sys; print(sys.executable)",pip show httpx | grep Location, andwhich python/which pip— all three paths must point into the same venv. -
The file is three lines:
text httpx==0.28.1 pydantic==2.14.3 pytest==9.2.0A
pyproject.tomladds project metadata and compatible ranges (httpx>=0.28,<0.29); the lockfile pins the full transitive tree, so two machines get identical code, which three top-level pins alone do not guarantee. -
Yes —
max_output_tokensis inside the hashed canonical JSON, so400vs200changes the key (d47bcbc1d529674cvs0beace24720f4245).sort_keys=Truemakes{"a":1,"b":2}and{"b":2,"a":1}hash identically — dict order is insertion order, not semantic order. -
Add a boolean flag (
argparseturns--dry-runinto the attributedry_run) and return before doing any work:python import argparse def main() -> int: p = argparse.ArgumentParser(description="Summarise ticket counts.") p.add_argument("csv_file", help="path to the tickets CSV") p.add_argument("--dry-run", action="store_true", help="show the parsed arguments and exit") args = p.parse_args() if args.dry_run: print(vars(args)) return 0 print("doing the real work on", args.csv_file) return 0 if __name__ == "__main__": raise SystemExit(main())console $ python3 cli_demo.py tickets.csv --dry-run {'csv_file': 'tickets.csv', 'dry_run': True} -
subprocess.run(["cat", filename], capture_output=True, text=True)— filenames containing; rm -rf ~,$(curl evil),a | shor backticks become literal arguments tocat, not shell syntax.
from datetime import datetime, timedelta
t = datetime.fromisoformat("2026-11-01T09:30:00+00:00") + timedelta(hours=72)
print(t.isoformat())
try:
datetime(2026, 11, 4, 12, 0) - t
except TypeError as e:
print("TypeError:", e)2026-11-04T09:30:00+00:00
TypeError: can't subtract offset-naive and offset-aware datetimesThe naive value has no timezone, so "how far apart are these two moments?" has no answer until you decide which zone it was in.
12. json stdlib; payload validation → pydantic (third-party, 01B.6); HTTP/2+pooling → httpx (third-party, 01B.5); YAML → pyyaml (third-party — TOML has tomllib, YAML deliberately does not); file hashing → hashlib stdlib.
13.
import tomllib
data = tomllib.loads("[project]\nname = 'x'\nversion = '0.1'\n[tool.demo]\nlevel = 3")
print(data["project"]["name"], data["tool"]["demo"]["level"])x 3loads takes a str; tomllib.load needs a binary file object (open(..., "rb")).
14. models holds data shapes, rules holds decisions, io holds format plumbing, cli holds argument parsing — each module has one reason to change. If classify lived in cli.py, io/rules tests and other callers would import the CLI module (pulling argparse/sys side effects) and the logic couldn't be reused without a CLI context.
15. python -c "import sys; print(sys.executable)" and pip -V/pip show requests | grep -i location — the interpreter path and the install location must agree; fix by activating the right venv or using python -m pip.
Check yourself#
- What is a module, and what makes a directory a package?A module is a
.pyfile (its name is the filename); a package is a directory of modules marked by__init__.py— or a namespace package without one (PEP 420). - Name the three everyday import forms and when each is preferable.
import x(module object, dotted access — best for several names),from x import y(direct names — best for one or two),import x as y(alias — for long names/disambiguation). Avoidimport *. - Why does
import jsonin your project folder sometimes load yourjson.pyinstead of the standard library's? How do you check which file won?The script's directory issys.path[0], searched before the stdlib.importlib.util.find_spec("json").originshows which file wins; rename your file. - What does
sys.moduleshave to do with "a module runs once"?sys.modulescaches module objects after first import; laterimportstatements return the cached object instead of re-executing the file. - What is
if __name__ == "__main__"for, and what doespython3 -m pkgrun?It distinguishes "run as script" (__main__) from "imported as module" (real name), guarding side effects.python3 -m pkgrunspkg/__main__.pywith the package onsys.path. - Why should
__init__.pystay light?It executes on everyimport pkg.anything; heavy imports there tax every consumer and can create circular-import cycles. - A file inside a package fails with
attempted relative import with no known parent package. What happened and what is the fix?The file was run by path, outside its package —..has no meaning. Runpython3 -m package.modulefrom the project root. - On Python 3.14 a circular import reports
cannot import name 'X' from 'billing' (consider renaming ...). Is the renaming hint the real problem? What is?No — for project-internal cycles on 3.13+ the hint is a red herring (it targets stdlib/library shadowing). The real problem is the import cycle; read the traceback's middle frames. - Why does
import billingsometimes survive a cycle thatfrom billing import TAX_RATEdoes not?import billingbinds the module object and resolves attributes lazily at call time;from billing import TAX_RATEneeds the attribute now, whilebillingis still mid-import. - When should you create a virtual environment, and what goes wrong without one?One per project, before installing packages — it isolates dependencies so projects can't corrupt each other's versions. Without it,
pip installwrites to the shared interpreter and projects fight. requirements.txtvspyproject.toml+ lockfile — which is which, and when do you need each?requirements.txtpins an environment ("install exactly this");pyproject.tomldeclares the project (metadata, ranges, scripts) and the lockfile pins the resolved transitive tree. Apps need both in practice: pyproject for declaration, lock/requirements for reproducible installs.- Name four supply-chain defences for
pip/uvinstalls.Copy names exactly, pin versions (==/lockfile), prefer widely-used packages, review the package/repo, use--require-hasheswhere possible, keep private packages on a private index. - Why is
secrets.token_hexright for API tokens whererandomis wrong?randomis a deterministic PRNG — its output can be predicted/reproduced.secretsuses OS entropy; tokens must be unguessable. datetime.now()vsdatetime.now(timezone.utc)— what is the practical difference?datetime.now()returns local wall-clock time with no timezone (naive — machine-dependent, can't mix with aware datetimes).now(timezone.utc)returns an aware instant — store/transmit UTC, convert for display.- For each:
httpxorurllib.requestfor a production HTTP client;hashlibor a third-party hash for cache keys;argparseortyperfor a quick internal CLI — justify each choice.httpx— pooling, timeouts, HTTP/2 are real gapsurlliblacks;hashlib— stdlib SHA-256 is exactly what cache keys need, no dependency;argparse— zero-dep stdlib floor is fine for a quick CLI,typerif you want nicer UX and accept the dependency.
Further resources#
- Python docs: The Python Tutorial — the official beginner path; modules and packages are covered in the "Modules" chapter.
- Python docs: Library reference and
sys.path/ import system — the authoritative reference for everything in Part 5. - PEP 8 — Style Guide and PEP 20 — The Zen of Python (
import thisprints it) — the conventions this path follows. - PEP 420 — Implicit Namespace Packages — the spec behind 2.2.
- Python Packaging User Guide —
pyproject.toml, wheels, sdists, entry points: the modern packaging reference (01B.1 applies it). - pip documentation and uv documentation — the two installers used in Part 4.
- PyPI — the package index itself; check names, versions and project links before installing.
venvdocs andsubprocesssecurity considerations — the official word on the two riskiest tools in the tour.- Real Python — Python Modules and Packages — a well-regarded tutorial if the import system still feels abstract.
← 01A.6 — Classes, Dataclasses and Enums | Module 01A overview | 01A.8 — Errors, Exceptions, Debugging and Logging →