classmethod Defines Named Constructors
@classmethod factories take strings, dicts, or foreign units and return real instances, and subclasses inherit them because cls is the actual receiver.
Page 2 of 6
@classmethod factories take strings, dicts, or foreign units and return real instances, and subclasses inherit them because cls is the actual receiver.
A loop variable is captured by name, not by value, so late-running lambdas all see the final count; a default parameter pins the value at definition time.
Without __bool__, truthiness falls back to __len__, and objects with neither are always truthy — define one to keep empty containers from sneaking through.
The else clause attached to a for loop runs only when no break fired, turning a search miss into structured control flow.
__len__ and __getitem__ alone make len, indexing, membership, and list() work, because Python falls back to the old sequence protocol for iteration.
is compares object identity while == compares contents; aliasing one list shows mutations propagating, and is None is the idiomatic test.
next() pulls one item with an optional default, and iter(callable, sentinel) streams calls until the sentinel shows up — no lists needed.
math.hypot computes Euclidean length from components and math.dist measures the gap between two points, both in n dimensions.
math.isclose replaces == on floats: relative tolerance absorbs rounding error, and abs_tol covers comparisons against zero that rel_tol cannot express.
typing.NewType stamps distinct types onto primitives for static checkers while the runtime value stays a plain int with zero overhead.
The / marker forces positional-only arguments and * forces keyword-only ones, so call sites stay self-documenting and misorders fail loudly.
A bounded queue.Queue plus a None sentinel lets producer and consumer threads hand work across safely, with blocking puts acting as built-in backpressure.
raise ... from keeps the caught exception as __cause__ so tracebacks and log aggregators show the root failure next to the rewritten error.
startswith and endswith accept tuples, so one call matches any of several prefixes or suffixes instead of chaining or-ed string comparisons.
strip, lstrip, and rstrip trim whitespace or any characters in a set from the ends; set-based stripping is not prefix removal, so use removeprefix for affixes.
Return codes travel through sys.exit: usage errors conventionally return 2, validation failures 1, and the value handed to sys.exit becomes the process status.
Locking each read-modify-write with `with lock:` makes four threads incrementing a shared counter lose no updates, and the lock releases automatically.
typing.Literal names an exact set of allowed values for static checkers; at runtime the annotation is documentation with no enforcement.
The same word can be one precomposed codepoint or a base letter plus a combining mark; unicodedata.normalize('NFC') makes both spellings compare equal.
urlsplit and parse_qs dissect a URL without touching the network, and urlencode with doseq=True turns list values back into repeated query keys.
literal_eval parses literal data — lists, dicts, tuples, strings — and refuses calls, arithmetic, and name lookups with ValueError instead of running them.
Size bitmasks and buffers with int.bit_length and int.bit_count: needed bits, popcount, and the Kernighan loop agree on every value shown.
Turn setup and teardown into a @contextmanager generator: commit on clean exit, roll back and re-raise on error, all without a class.
Compute CRC-32 checksums over byte payloads and chain chunked calls by passing the previous value back in, so streamed bytes hash identically to the whole.
Clone dataclass records with asdict, astuple, and replace: copies run deep through nested dataclasses, and replace rewrites fields without touching originals.
Compute quotients and remainders with //, %, and divmod: Python floors toward negative infinity, so negative operands still satisfy q*b+r==a.
Split an ExceptionGroup by type with except*: each clause runs for every matching member, and unmatched types pass through untouched.
generators accept injected values through .send() after priming with next(), and close() ends them permanently by raising GeneratorExit inside.
getsizeof reports one object's own bytes including its header, excluding referenced contents — the nested-container test shows outer lists store pointers.
min and max take a key function to rank derived values and a default to answer empty sequences instead of raising ValueError; the original objects come back.
Derive password verifiers with hashlib.pbkdf2_hmac under a per-record salt, then confirm candidates with secrets.compare_digest for constant-time comparison.
monotonic and perf_counter clocks only move forward, making them the tools for durations; time.time() stays reserved for wall-clock timestamps.
re.match anchors at string start while re.search scans for the first hit; the two agree only when the pattern pins to position zero.
repr targets developers with an unambiguous form, str targets readers; containers render items with repr only, and each method falls back differently.
reprlib caps entries per container and nesting depth when stringifying large structures, so logs and reports stay readable without hand-rolled truncation.
round() breaks exact .5 ties toward the even neighbor while binary float storage decides the rest; printed results show both, plus the Decimal escape hatch.
list.sort is stable, so sorting by the least significant key first, then bigger keys, composes multi-pass orderings; tuple keys fold it into one pass.
sys.intern returns the canonical object for each string value, so equal strings built at runtime share identity, trimming memory and speeding comparisons.
timeit repeats a statement many times and repeat() returns one result per round, so the minimum — least disturbed by background load — is the honest number.
Pack fixed-shape records as tuples: they are immutable on assignment, hashable as dict keys, and single-element forms need the trailing comma.
UserDict routes every write and read through __setitem__ and __getitem__, so normalization and validation survive update(), construction, and setdefault too.
utf-8-sig writes the BOM on encode and consumes it on decode, while plain utf-8 leaves U+FEFF glued to the first CSV field after a round trip.
Define Money-style value objects where equality compares fields: __eq__ without __hash__ makes instances unhashable, so the pair must agree.
The walrus operator assigns inside expressions: bound-and-tested conditions, chunked while loops that end on empty reads, and deduplication in comprehensions.
any stops at the first truthy item and all at the first falsy one, empty inputs default to False and True, and next() finds the decisive item itself.
bytearray is the mutable twin of bytes: slices reassign fixed-width fields, single bytes read as integers, and str conversion always names an encoding.
collections.abc classes answer isinstance for any object exposing the right protocol, and Sequence.register accepts unrelated classes as virtual subclasses.
Tallying occurrences into a counts array replays values in order with zero pairwise comparisons, in O(n + max_value) time for small known ranges.
A class with __iter__ returning self and __next__ raising StopIteration plugs into for-loops, iter(), and next() like any builtin sequence.
isoformat() renders an aware datetime and fromisoformat() parses it back losslessly; Python 3.11 also accepts the web-style Z suffix and explicit offsets.
get_close_matches ranks known strings by similarity with a cutoff floor, turning mistyped CLI commands into a did-you-mean suggestion list.
html.escape turns angle brackets, ampersands, and quotes into entities so untrusted text stays inert, and unescape reverses the mapping on read-back.
int(text, base) reads digits in the given radix, base 0 trusts 0b/0o/0x prefixes, and format or bin/oct/hex write integers back out in any base.
tee clones a single-pass iterator into independent cursors that each see the full stream, buffering whatever one branch reads ahead of the other.
indent renders readable trees, compact separators squeeze bytes onto one line, and sort_keys makes equal dicts serialize byte-identically.
math.comb counts unordered picks, math.perm counts ordered ones, k greater than n yields 0 instead of an error, and negative inputs raise ValueError.
A monotonic stack of unresolved indices answers the next strictly larger value for every position in one linear pass instead of scanning right repeatedly.
methodcaller(name, *args) builds a reusable callable that invokes one method with fixed arguments on every item, turning dict.get calls into sort keys.
The three-argument pow(x, y, mod) keeps intermediate values small where x**y would explode, and pow(x, -1, mod) computes a modular inverse or raises ValueError.
A backreference re-matches exactly what its group captured: repeated words fail a lint, quote pairs must close with the same character, keys equal values.
re.escape turns every metacharacter in untrusted text into a literal, so a dot searches for a dot instead of any character and composed templates stay exact.
By default ^ and $ match whole-string ends only; MULTILINE moves them to every line break while DOTALL lets a dot cross newlines to span several lines.
The re.VERBOSE flag ignores whitespace and # comments inside a pattern, so multi-line regexes document their groups and still match exactly the same text.
Slices clamp out-of-range bounds instead of raising, negative indices count from the end, slice objects are reusable by name, slice assignment resizes lists.
linear_regression returns slope and intercept in one call and correlation rates the fit, so predictions and linearity checks need no external packages.
io.StringIO wraps a string as an in-memory text stream, so print(file=...) and csv writers redirect into a buffer instead of touching the filesystem.
super() calls the next class in the C3 linearization rather than a fixed parent: mixin order decides the chain and conflicting orders fail at definition.
Workers wait on one shared Event flag: wait(timeout) sleeps without busy looping, set() wakes every waiter at once, and join() confirms the shutdown.
A deque as a sliding window evicts timestamps older than the horizon in one amortized pass, so counting pings in the last N seconds stays O(1) per call.
struct.pack and unpack move values into fixed-layout byte strings; iter_unpack walks a buffer without slicing, and wrong sizes raise struct.error.
Structure a CLI with argparse subparsers so each verb owns its flags and help text, and the top level stays a clean verb list.
Parse Python source with ast, insert a trace call with NodeTransformer, and unparse the rewritten tree back to valid source.
Bound concurrent coroutines with a semaphore inside gather so a large batch does not open every connection at once.
Move blocking work off the event loop with asyncio.to_thread so synchronous checks run in worker threads while other coroutines continue.
Register atexit cleanup hooks, observe reverse execution order, unregister one callback, and keep shutdown work deterministic.
Layer defaults and environment overrides with configparser read_string calls, keeping configuration precedence explicit and easy to test.
Enter async context managers dynamically with AsyncExitStack, register a callback, and watch cleanup run in reverse order after the block.
Silence only the specific exception you expect with contextlib.suppress, keeping every other failure loud.
Make dataclasses safe dictionary keys and set members with frozen=True and eq, so value semantics replace tuples of fields.
Mark trailing dataclass fields with KW_ONLY so callers must pass them by name, inspect keyword-only fields, and catch the positional TypeError.
Drive Decimal precision and rounding explicitly with getcontext and localcontext, and quantize amounts without binary floating point drift.
Wrap cross-cutting concerns in decorators with functools.wraps so callers keep signatures and docstrings while gaining timing or retry.
Parse a multipart MIME message with email.parser, list each content type, and read text bodies and attachment payloads.
Format and parse email timestamps with email.utils, compare timezone offsets, and render the GMT label required by message headers.
Build enums with auto numbering and guard duplicate values with the unique decorator, then look members up by name, value, or identity.
Compare individual files and whole directory trees with filecmp, separating matches, mismatches, and files missing on one side.
Register singledispatchmethod overloads by argument type, dispatch through a class instance, and fall back to a base implementation.
Chain generator expressions so large inputs stream through the pipeline one element at a time, with no intermediate lists.
Subclass html.parser to collect headings, links, and image sources from a page while keeping the parser streaming and dependency free.
Load a module by dotted name with importlib, reload it in place, and inspect a spec with find_spec without executing the module.
Read installed package versions with importlib.metadata, handle PackageNotFoundError, and inspect distribution metadata and files.
Read packaged files with importlib.resources.files, inspect a Traversable, and materialize it through as_file for path-based APIs.
Read a signature with inspect.signature, bind positional and keyword arguments, apply defaults, and report missing or extra parameters.
Filter parallel sequences with itertools.compress: pair data with boolean selectors, stop at the shorter input, and build selectors from predicates.
Use itertools count, cycle, and repeat to build lazy infinite streams, then trim them with islice into finite results.
Group consecutive equal keys with itertools.groupby — and remember it only groups runs, so sort by the key first.
Unpack argument tuples with itertools.starmap, apply a function to each row, consume a lazy generator, and handle an empty input list.
Subclass json.JSONEncoder to serialize Decimal, date, and datetime values predictably, with a default fallback and safe round trips.
Parse JSON numbers with parse_float=Decimal, compare the float and Decimal totals, and keep currency arithmetic exact.
Slice a bytearray through memoryview to inspect and patch large buffers in place, avoiding full copies at every processing step.