Standard-Library Selections¶
Check the standard library before adding a dependency or writing infrastructure code. These selections cover commonly overlooked tools and choices that are easy to get wrong.
Preferred Selections¶
| Need | Prefer | Notes |
|---|---|---|
| Filesystem paths | pathlib.Path |
Compose and inspect paths without manual separator handling. |
| Packaged files | importlib.resources |
Works for installed packages that are not ordinary filesystem directories. |
| Temporary files | tempfile |
Handles secure creation and cleanup; avoid predictable names. |
| TOML input | tomllib |
Built-in reader on Python 3.11+; it does not write TOML. |
| Time zones | zoneinfo |
Use aware datetimes for instants crossing system boundaries. |
| Decimal contracts | decimal.Decimal |
Construct from strings when exact decimal input matters. |
| String-valued enums | enum.StrEnum |
Available on Python 3.11+; useful for stable finite string values. |
| Subprocesses | subprocess.run |
Pass an argument sequence, set a timeout, and avoid shell=True by default. |
| Dynamic cleanup | contextlib.ExitStack |
Composes a runtime-determined set of context managers and callbacks. |
| Immutable records | dataclasses |
Use frozen=True only when shallow immutability matches the domain. |
Frequently Overlooked Gems¶
collections.Counterfor multisets and frequencies;dequefor efficient operations at both ends;defaultdictfor uniform missing-value construction.itertoolsfor lazy chaining, batching, pairing, accumulation, and combinatorics. Prefer these primitives to hand-written iterator state machines.functools.cachefor unbounded memoization of pure calls andcached_propertyfor stable per-instance computation. Confirm memory retention and invalidation semantics first.operatorfunctions such asitemgetterandattrgetterfor declarative sort/group keys.graphlib.TopologicalSorterfor dependency ordering and cycle detection.shlex.joinfor human-readable POSIX command display. It is not a reason to execute through a shell.secretsfor tokens and security-sensitive randomness; userandomfor simulation and non-security sampling.uuid.uuid7on Python 3.14+ when sortable time-based UUIDs fit the storage contract; otherwise select a UUID version intentionally.
Selection Traps¶
Path.read_text()andwrite_text()are convenient for bounded content, not streaming large files.dataclasses.asdict()recursively deep-copies nested dataclasses and collections; avoid it when identity, custom serialization, or large graphs matter.functools.cacheretains arguments and results until the cache is cleared; do not put it on unbounded request-key spaces.datetime.utcnow()returns a naive datetime. Preferdatetime.now(timezone.utc)for an aware UTC value.pickleis not safe for untrusted data. Choose a schema-based format at trust boundaries.subprocessargument lists prevent shell parsing, but values still require domain validation when they select files, executables, or privileged behavior.