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
Test yourself on Standard Library, Packaging and Tooling
Ten questions, with the answer and explanation after each one.