Python Atlas
Standard library & async

Standard library quick reference

A selection map for common APIs, tradeoffs, pitfalls, and further practice.

Use this page as a decision aid. The official Python documentation remains the authoritative API reference for your installed Python version.

Files, processes, and runtime

TaskAPINotes
Compose pathspathlib.Path and /Do not concatenate separators
Read small textPath.read_text(encoding="utf-8")Loads the whole file
Stream textPath.open()Use a context manager
Copy/move treesshutilPrefer high-level operations
Traverse efficientlyos.scandir()Decide whether to follow symlinks
Environmentos.environ, os.getenv()Values are strings; avoid secret logging
External commandsubprocess.run([...], check=True)Avoid shell=True for untrusted input
CLI parsingargparseProduces help and validation
Runtime/streamssys.argv, sys.stderr, sys.version_infoKeep library code process-neutral
Temporary filestempfileContext-managed and race-resistant

Data, text, and numbers

TaskAPINotes
JSONjson.load, json.dumpValidate shape after parsing
CSVcsv.reader, csv.DictReaderOpen files with newline=""
Pattern matchingrePrefer plain string methods for simple cases
Immutable recordsdataclasses.dataclass(frozen=True)More evolvable than raw tuples
Count valuescollections.CounterMissing entries read as zero
FIFO/double-ended queuecollections.dequeFast operations at both ends
Exact decimal rulesdecimal.DecimalConstruct from strings
Exact ratiosfractions.FractionNumerators can grow large
Robust float summationmath.fsumStill produces a float
Descriptive measuresstatisticsState population/sample and missing-data policy
Secure random tokenssecretsDo not use random for security

Dates and clocks

NeedAPI
Current instantdatetime.now(timezone.utc)
IANA timezonezoneinfo.ZoneInfo("Area/City")
Machine timestampdatetime.isoformat()
Fixed durationdatetime.timedelta
Elapsed deadlinetime.monotonic() or event-loop time
Benchmarktime.perf_counter()

Never mix naive and aware timestamps. Store UTC instants, retain the timezone name for future local schedules, and define daylight-saving policies.

Iteration

NeedAPI
Lazy custom transformGenerator expression/function
Slice an iteratoritertools.islice()
Batch lazilyitertools.batched()
Flatten iterablesitertools.chain()
Adjacent groupingitertools.groupby()
Cartesian productitertools.product()
Running totalsitertools.accumulate()

Estimate combinatoric output sizes and never consume an infinite iterator without a bound.

HTTP and URLs

NeedAPIBoundary
Query encodingurllib.parse.urlencode()Not for path segments
Path segment encodingurllib.parse.quote()Choose safe deliberately
Parse URLurlsplit()Parsing is not validation
Basic sync requesturllib.request.urlopen()Set timeout and size limits
HTTP errorsurllib.error.HTTPErrorResponse-like exception
Network errorsurllib.error.URLErrorInspect reason

For high-volume clients, pooled connections, granular timeouts, or native async HTTP, evaluate a maintained third-party client. Dependency-free does not automatically mean simpler operations.

Asyncio

NeedAPIGuidance
Program boundaryasyncio.run(main())Usually once
Related child tasksasyncio.TaskGroupPreferred structured scope
Ordered aggregate awaitasyncio.gather()Understand failure semantics
Timeout scopeasyncio.timeout()Catch TimeoutError outside
Blocking I/O bridgeasyncio.to_thread()Blocking call still needs a timeout
Exclusive accessasyncio.LockKeep critical section short
Capacity limitasyncio.SemaphoreNot a rate limiter
State notificationasyncio.Event, ConditionConditions wait on predicates
Ownership transferasyncio.Queue(maxsize=n)Bounded queues create backpressure
TCP streamopen_connection()Drain writes and close writers

Failure checklist

Before shipping code that owns resources or concurrent work, ask:

  1. Is every file, socket, task, executor, and process owned by a visible scope?
  2. Are all external waits bounded by a timeout or deadline?
  3. Can input grow memory without a limit?
  4. What happens if cancellation arrives at each await?
  5. Can two workers violate a shared invariant?
  6. Are errors preserved with enough type and context to act on?
  7. Does shutdown stop intake, finish or abandon owned work, and release resources?

Capstone practice

Build a command-line URL checker:

  1. read URLs line-by-line from a UTF-8 file;
  2. validate HTTPS scheme and an explicit host allowlist;
  3. process checks concurrently under a TaskGroup;
  4. bridge urllib.request with asyncio.to_thread;
  5. enforce both per-request timeouts and one total deadline;
  6. limit concurrency with a semaphore and input buffering with a bounded queue;
  7. aggregate status counts with Counter;
  8. emit timestamped JSON using aware UTC values;
  9. write output through an atomic replacement;
  10. test cancellation, DNS failure, oversized responses, duplicate URLs, and daylight-saving display conversion.

Explain whether a synchronous thread-pool design would be simpler. Async is justified only when its operational benefits outweigh the additional cancellation and lifetime complexity.

LEARNING RECORD

Finish this lesson

Mark it complete when you can explain the main decision without looking.

KNOWLEDGE CHECK

Standard library quick reference

1A dependency-free async URL checker must avoid blocking the loop, cap concurrent requests, and bound queued input. Which combination fits?
2When is a maintained third-party HTTP client a better starting point than urllib?