Skip to content

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.Counter for multisets and frequencies; deque for efficient operations at both ends; defaultdict for uniform missing-value construction.
  • itertools for lazy chaining, batching, pairing, accumulation, and combinatorics. Prefer these primitives to hand-written iterator state machines.
  • functools.cache for unbounded memoization of pure calls and cached_property for stable per-instance computation. Confirm memory retention and invalidation semantics first.
  • operator functions such as itemgetter and attrgetter for declarative sort/group keys.
  • graphlib.TopologicalSorter for dependency ordering and cycle detection.
  • shlex.join for human-readable POSIX command display. It is not a reason to execute through a shell.
  • secrets for tokens and security-sensitive randomness; use random for simulation and non-security sampling.
  • uuid.uuid7 on Python 3.14+ when sortable time-based UUIDs fit the storage contract; otherwise select a UUID version intentionally.

Selection Traps

  • Path.read_text() and write_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.cache retains arguments and results until the cache is cleared; do not put it on unbounded request-key spaces.
  • datetime.utcnow() returns a naive datetime. Prefer datetime.now(timezone.utc) for an aware UTC value.
  • pickle is not safe for untrusted data. Choose a schema-based format at trust boundaries.
  • subprocess argument lists prevent shell parsing, but values still require domain validation when they select files, executables, or privileged behavior.