Explaining Python Standard Library
When asked about any stdlib entity, first classify it, then answer with structure:
- Category: builtin type / stdlib module / function / method / protocol
- Signature or construction
- Key behaviors, especially non-obvious ones
- Minimal runnable example
- Related entities worth knowing
Example for a builtin type (bool):
Python>>> issubclass(bool, int) # bool is an int subclass, only 2 instances True >>> True + True 2 >>> bool([0]) # non-empty list -> truthy, even though element is falsy True
Example for a stdlib module function (itertools.groupby):
Pythonfrom itertools import groupby # groupby only groups CONSECUTIVE equal keys — a frequent gotcha data = [1, 1, 2, 1] print([(k, list(g)) for k, g in groupby(data)]) # [(1, [1, 1]), (2, [2]), (1, [1])] -- NOT grouped by value across the list # fix: sort first if you want all equal keys grouped together
Progress:
- Determine scope: single function/method, a type, or an entire module?
- If scope is a whole module (e.g., "explain
collections"), give a one-line summary of each major member first, then drill into the one most relevant to the user's actual goal — don't dump the full API. - If scope is a single type/function, go directly to signature + behavior + example.
- If the question spans multiple stdlib areas (e.g., "how do I dedupe while preserving order" touches
dict,set, anditertools), briefly compare 2-3 approaches with trade-offs instead of picking one silently. - Identify surprising/edge-case behavior specific to that entity (mutability, ordering, laziness, locale/timezone sensitivity, etc.)
- Give a short, correct, copy-pasteable example demonstrating the surprising behavior, not just the happy path.
- Note version-specific changes if relevant ("changed in 3.7", "added in 3.9") — flag uncertainty rather than guessing.
- Cross-reference related types/functions/modules when it clarifies behavior or offers a better tool for the job.
Example 1: Single builtin type
Input: "Why does bool([0]) == True but bool(0) == False?"
Output:
Truth-value testing treats as false:
None,False, numeric zero (0,0.0), and empty containers ('',[],{},(),set()) — or objects whose__bool__/__len__say so.[0]is a list of length 1 (truthy container), even though its only element is falsy.0is itself a falsy number. Container truthiness depends on length, not on the truthiness of contents.
Example 2: Module-level ambiguous query
Input: "Tell me about the collections module."
Output:
collectionsprovides specialized container types beyond the builtins:
Counter— multiset/frequency counting (Counter("aab")→Counter({'a': 2, 'b': 1}))defaultdict— dict with a factory for missing keys, avoidsKeyErrorboilerplatedeque— O(1) appends/pops from both ends, unlikelist's O(n)pop(0)namedtuple— lightweight immutable record type with named fieldsOrderedDict— mostly redundant since dicts preserve insertion order (3.7+), but still useful formove_to_end()and equality that considers orderWhich one matches what you're building? If it's "count occurrences,"
Counteris the direct answer — e.g.Counter(words).most_common(3).
Example 3: Cross-module comparison Input: "How do I remove duplicates from a list but keep order?" Output:
Three options, trade-offs differ:
Pythonlist(dict.fromkeys(items)) # simplest, O(n), Python 3.7+ dict order guarantee seen = set() [x for x in items if not (x in seen or seen.add(x))] # explicit, works pre-3.7 too from more_itertools import unique_everseen # not stdlib — only if already a dependencyDefault recommendation:
list(dict.fromkeys(items))— concise and relies on documented dict behavior, not an implementation detail.
Example 4: Datetime quirk
Input: "Why did subtracting two datetime objects give unexpected results?"
Output:
datetimesubtraction returns atimedelta, which stores onlydays,seconds, andmicroseconds— accessing.secondsalone on a multi-day delta gives just the remainder seconds, not the total:Pythonfrom datetime import datetime d = datetime(2024, 1, 3) - datetime(2024, 1, 1, 23, 0, 0) print(d.days, d.seconds) # 0 1200 (1 hour left after the days) print(d.total_seconds()) # 3600.0 total elapsed seconds — the one you usually wantAlso: naive vs. aware datetimes can't be subtracted/compared (
TypeError) — checkd.tzinfo is Nonewhen debugging.
- Show behavior via runnable snippets, not prose-only claims.
- For containers/types: state mutability, hashability, ordering guarantees explicitly (e.g., "tuples are hashable if all elements are hashable; lists never are").
- For modules: summarize breadth first if the question is broad, then go deep on the part matching the user's actual need.
- When multiple stdlib tools solve the same problem, name 2-3 and give the default recommendation rather than an exhaustive survey.
- Always state Python version when behavior is version-dependent instead of assuming the latest release.
- Don't answer a whole-module question with a single deep-dive on one function — scan the module's main members first.
- Don't treat
==equality as identity; call outisonly when singleton/identity actually matters (e.g.,True/False/None, small int caching). - Don't assume container truthiness or equality without checking length/type rules (e.g.,
bool("0")isTrue). - Don't state stdlib behavior from memory without flagging version sensitivity when unsure — signatures and defaults do change across releases (e.g.,
dictordering became guaranteed in 3.7).