binascii hexlify Formats Bytes and b85 Packs Text
Format binary digests with delimiter support via binascii.hexlify and pack bytes compactly with base64.b85encode compared against Base64 overhead.
Format binary digests with delimiter support via binascii.hexlify and pack bytes compactly with base64.b85encode compared against Base64 overhead.
Use contextlib.nullcontext as a drop-in no-op context manager when a lock, trace, or writer is optional, avoiding duplicated with-block bodies.
Handle CSV rows with extra or missing trailing columns cleanly using csv.DictReader restkey and restval before normalizing via DictWriter.
Declare initialization-only parameters with dataclasses.InitVar so __post_init__ can derive or normalize state without leaking extra fields to asdict.
Parse UTC Z timestamps, compact dates, and ISO week strings via Python 3.11 datetime.fromisoformat, rejecting naive timestamps without tzinfo.
Attach preset arguments to class methods with functools.partialmethod so the descriptor protocol preserves self on instances and subclasses alike.
Contrast heapq.heappushpop and heapq.heapreplace in fixed-size top-k buffers: heappushpop keeps out smaller items, while heapreplace always pops first.
Mutate an in-memory BytesIO stream through getbuffer() without copying bytes, and release the memoryview cleanly before resizing or closing.
Check numeric arguments with numbers.Integral and numbers.Real across int, float, and Fraction while explicitly rejecting bool subclasses of int.
Audit text replacements in one pass with re.subn returning (text, count), and scan bounded slices using compiled pattern pos and endpos offsets.
Subclass string.Formatter to allowlist lookup keys, block attribute traversal in format strings, and mask sensitive values automatically.
Resolve ambiguous fall-back clock times with datetime fold=0 and fold=1 under ZoneInfo, and detect nonexistent spring-forward gaps via UTC round-trips.
Teach the + operator to work on your class by defining __add__, and make instances print readably with __repr__, returning NotImplemented for wrong types.
Implement __contains__ on a class so membership checks run your logic; the fallback when missing is __iter__, not __len__.
Get the most frequent values with statistics.multimode, which keeps every tied value in first-seen order instead of returning one arbitrary winner.
Center strings in a fixed width with str.center, which splits leftover padding between the sides, rejects multi-character fills, and never truncates.
Count substring occurrences with str.count, which scans left to right and never counts the same bytes twice — the classic non-overlapping trap.
Locate substrings with str.find when absence is expected and str.index when it is not, while the in operator answers pure membership without a position.
Render strings with str.format positional, named, and indexed fields — the one path where the template itself can live in a variable, unlike f-strings.
Gate input by character class with isalpha, isalnum, and isspace — all three return False for empty strings, so strip before judging user input.
Trim known prefixes and suffixes with removeprefix and removesuffix, which return the string untouched when the affix is absent instead of raising.
Validate routing prefixes with str.startswith, which accepts a tuple of candidates and a start offset so one call replaces or-ed comparisons.
Flip letter case in place with str.swapcase and gate display rules with istitle, isupper, and islower, which all return False for empty or digit-only strings.
Render datetimes with strftime format codes — %Y %m %d %H %M %S for fields, %f for microseconds — and round-trip the output through strptime.
doctest.testmod executes every >>> example in docstrings and compares printed results, turning documentation into tests that catch drift.
East Asian wide glyphs occupy two terminal cells, so column padding must measure display width with unicodedata.east_asian_width before ljust.
Maintain prefix sums with index & -index jumps so point updates and range queries cost O(log n) each, and changed entries never force a full rescan.
Sort edges by weight, union the endpoints when their roots differ, and stop after n-1 picks: the result is a minimum spanning tree with cycle rejection.
Track one OrderedDict bucket per use frequency and evict the oldest key at the lowest frequency, promoting keys on every get and put.
os.scandir yields DirEntry objects that carry scan data, so is_dir() and stat() skip the extra syscall per file that os.listdir would need.
Store range sums in a 4n array indexed like a binary tree so point updates and arbitrary range queries both cost O(log n) without rescanning elements.
Postfix expressions evaluate with one stack: push numbers, pop two operands per operator, and the final remainder is the whole expression's value.
correlation() returns the Pearson coefficient between two series while covariance() keeps raw units; self-correlation is 1 and linear rescaling preserves r.
tokenize.generate_tokens applies lexical rules, so COMMENT tokens never include # characters that live inside string literals.
patch() swaps the module-level datetime name for a Mock whose now() returns an injected moment, so both greeting branches run without a real clock.
fmean applies weights, harmonic_mean averages equal-distance speeds honestly, and geometric_mean fits growth factors like 2x then 8x.
base64.b32encode emits only A-Z and 2-7 so backup codes survive handwriting and reading aloud; decoding restores the stripped padding with a modulo trick.
Two dicts kept in sync give both directions of a lookup; adds and removes must touch both sides and duplicates must be rejected at the entry point.
Recursive inorder, preorder, and postorder walks visit a binary tree in three different orders, and a deque drives the level-order variant.
True, 1, and 1.0 compare equal and hash equal, so they occupy one dict slot; normalize keys to strings when the source type has to stay distinguishable.
Iterating bytes yields integers while iterating str yields one-character strings, so comparing bytes against str silently fails until you decode.
Bottom-up DP computes the fewest coins per amount and a choice table backtracks the exact denominations, returning -1 when the amount is unreachable.
os.path.commonpath computes the longest common parent for grouping and prefix stripping; comparing it against a base directory detects escaped paths.
field(metadata=) hangs display hints on dataclass fields, and fields() returns them as read-only mappings that drive formatting and serialization.
deque.rotate(-1) slides the chosen head item to the tail in one in-place step, turning a fixed list of endpoints into a fair round-robin selector.
dict.fromkeys binds every key to the same mutable object, so appending through one key mutates all rows; a comprehension builds an independent container.
Subclass dict and implement __missing__ to give subscript lookups a custom fallback or a clearer KeyError; .get and membership checks bypass the hook.
Adding or deleting keys while iterating a dict raises RuntimeError after the mutation lands, so structural changes need a key snapshot or a value-only pass.
dict.pop removes a key and returns its value, honoring a fallback for missing keys, while popitem pops the most recently inserted pair and raises on empty maps.
len on str counts code points while len of the UTF-8 encoding counts bytes, so the same text reports different sizes at the language and transport layers.
expandtabs walks each tab to the next tab stop so tab-separated rows line up in a terminal; a tab size wider than the longest cell keeps columns aligned.
fileinput reads CLI file arguments in sequence, tracks global and per-file line numbers, and rewrites files in place with a backup extension.
findall returns plain strings for one capture group but tuples once two or more groups appear, a shape change that trips naive parsers.
Slow and fast pointers meet inside a cycle; resetting one to the head and walking again at equal speed lands on the entry node.
__getattr__ runs only after normal lookup fails, so a settings wrapper can serve defaults lazily while real typos still raise AttributeError.
glob matches single levels with *, crosses directories only when ** is paired with recursive=True; results arrive in directory order, so sort them.
str.isprintable flags control, format and non-ASCII space characters, so one comprehension lists suspicious code points in untrusted input before storing.
Reversing a singly linked list needs three pointers: remember the successor, flip the link, and walk once so prev ends up the new head.
[[0] * cols] * rows copies row references, so writing one cell appears in every row; a comprehension allocates a fresh list per row and keeps edits local.
math.remainder snaps to the nearest multiple so results land inside half the divisor, while % follows the divisor sign and fmod follows the dividend.
ord returns the code point behind a character and chr inverts it, so char-level text math works on Unicode strings that iterate one code point at a time.
random.Random(seed) makes shuffle reproducible: the same deck reshuffled with the same seed replays card-for-card, which is what deal logs and tests need.
reversed hands back a one-shot reverse iterator instead of copying, leaving the sequence untouched, while slicing [::-1] allocates a re-usable list.
Set operators |, &, -, and ^ compose permission coverage checks directly, with union, intersection, difference, and issubset methods as named equivalents.
A deque of indices kept value-decreasing answers each sliding-window maximum in amortized constant time because every index enters and leaves the queue once.
No-argument split() treats any whitespace run as one separator and drops the edges, while rsplit with maxsplit keeps the left side intact for extension splits.
str.join is the separator method: it accepts any iterable of strings, requires conversion for numbers, and yields an empty string for an empty iterable.
str.replace accepts an optional count that limits replacement to the first N occurrences, enough for tiered masking without splitting strings.
string.ascii_uppercase plus string.digits defines the 36 legal characters for redeem codes; normalization absorbs separators, spaces and casing.
Annotated attaches validation markers next to field types, and get_type_hints with include_extras recovers them for runtime checks.
get_origin and get_args split generic aliases at runtime: list[int] yields list and int, unions expose their members, plain types expose nothing.
unicodedata.category assigns every character a class code, so sanitizers can whitelist letters and punctuation while dropping control and format characters.
Sort each word letters into a canonical key so anagrams land in the same bucket, then aggregate with defaultdict and rank groups by size.
Push openers on a stack and require each closer to mirror the stack top, so crossed pairs, stray closers, and unclosed openers all fail loudly.
date(year, month, day) validates on construction: impossible dates raise ValueError with the exact rule instead of rolling into the next month.
Run SequenceMatcher.get_opcodes over word lists to get equal, replace, delete, and insert ranges, so a diff describes sentence edits instead of whole lines.
Sentinel head and tail nodes make append and unlink constant-time with no None checks, and iteration walks head.next until it reaches the tail sentinel.
Build XML with Element and SubElement, serialize with tostring, pretty-print with indent, then parse it back with fromstring and read values by path lookup.
Index rows by id, attach each child under its parent reference, and collect roots separately, turning flat rows into a nested tree in one pass.
Slice a byte payload into fixed-width rows of offset, two-digit hex, and printable characters so binary data stays readable in logs.
Gate user-supplied field names behind str.isidentifier and keyword.iskeyword or issoftkeyword so dynamic attributes never collide with reserved syntax.
Flatten arbitrarily nested lists with an explicit iterator stack, so a thousand levels deep still works where recursion would hit its limit.
Catch json.JSONDecodeError and read msg, pos, lineno, and colno to show exactly where a malformed payload stopped parsing.
Kadane's scan extends or restarts the running subarray at each item and records the best window, handling all-negative arrays correctly.
Slice assignment replaces, inserts, or deletes ranges in place; the assigned sequence can have any length, so the list resizes around it.
Push onto an auxiliary stack that tracks the running minimum alongside the main stack, so pop and get_min stay O(1) with no rescanning.
Split digit runs out of names and compare them as integers, so report-2 sorts before report-10 and zero padding stops changing the order.
Walk two pointers inward from both ends, skipping non-alphanumeric characters and comparing lowercased letters, so punctuation-laden phrases still verify.
pickle round trips tuples that JSON silently widens to lists while None survives as null; loads must only ever receive payloads your own system produced.
Build one prefix array up front, then answer any range sum query with a single subtraction instead of re-summing the slice every time.
Build a FIFO queue from two stacks: pour the inbox once when the outbox empties, so every element moves at most twice and operations stay amortized O(1).
With a seeded Random, sample draws without replacement and rejects oversized k, choices draws with replacement under weights, shuffle reorders in place.
Greedy quantifiers stretch to the longest span and lazy quantifiers, written with an extra ?, stop at the shortest span that still succeeds.
Encode runs of repeated characters as count-plus-char pairs and expand them back, rejecting a dangling trailing count instead of dropping it.
Split a value stream across two heapq heaps so every insert rebalances the halves and yields the exact running median without re-sorting.
Walk both ends of a sorted array inward: move the left pointer when the pair sum is too small, the right one when it is too big.
A function with *args, keyword-only defaults, and **kwargs accepts extra positional names and keyword values, and call sites unpack them back.
BytesIO wraps an in-memory byte buffer in the file interface: writes, seeks, readline, getvalue, and readinto all work without touching disk.
A class with __call__ produces instances that work anywhere a function fits, such as sort keys, and callable() reports the capability.
Python compares chained relations left to right with the middle operand evaluated once, so 0 < x < 10 reads like math and works like it.