Standard Library, Packaging and Tooling
Know how imports really work, how to isolate and pin dependencies, and the standard-library traps (datetimes, decimals, JSON, regex, subprocess, encodings) that interviewers love.
Key points
- 1
A module runs once per process and is cached in
sys.modules. A script runs as__main__, so importing it by name executes it a second time. - 2
Use
python -m pkg.modulefor code that uses relative imports: it imports the package first and puts the working directory onsys.path[0]. - 3
Isolate projects in a virtual environment, use
pipxfor CLI tools, and pin transitive dependencies with a lock file (uv.lock, poetry.lock or pip-tools output). - 4
Keep datetimes timezone-aware (
datetime.now(UTC),zoneinfo). Same-tzinfo arithmetic is wall-clock, so convert to UTC to measure real elapsed time. - 5
Build
Decimalvalues from strings, and choose the rounding mode explicitly; the default is half-to-even, likeround(). - 6
Run subprocesses with a list of arguments,
check=Trueandcommunicate()/run(), nevershell=Truewith user input. - 7
Always pass
encoding="utf-8"toopen(); the default is the locale encoding until UTF-8 mode becomes the default in 3.15 (PEP 686).
Common traps
from config import Xcopies the value, soimportlib.reload(config)does not updateX.$in a regex matches before a trailing newline; usere.fullmatchor\Zfor validation.Path("/srv") / user_valuedrops the base whenuser_valueis absolute.
Read the source
Further reading
Suggest a resource- Python tutorial: Virtual environments and packages(opens in a new tab)Creating a venv, installing with pip and pinning requirements.Docsdocs.python.orgEditor’s pick
- Python Packaging User Guide: Packaging Python projects(opens in a new tab)pyproject.toml, build backends and publishing a package, end to end.Docspackaging.python.orgEditor’s pick
- pathlib: object-oriented filesystem paths(opens in a new tab)The modern way to build, inspect and walk paths instead of os.path.Docsdocs.python.orgEditor’s pick
Test yourself on Standard Library, Packaging and Tooling
Ten questions, with the answer and explanation after each one.