mmap Maps Files Without Full Reads
Map a file into memory with mmap, patch bytes in place, and observe read-only mappings reject writes with TypeError.
Page 3 of 6
Map a file into memory with mmap, patch bytes in place, and observe read-only mappings reject writes with TypeError.
Fan out CPU-bound work with multiprocessing Pool, using map, starmap, and imap_unordered while the main process stays responsive.
Type a decorator with ParamSpec so the wrapped function keeps its exact parameters and return type for callers and type checkers alike.
Compose and normalize filesystem paths with pathlib so relative segments, parents, and safety checks read as object operations.
Use possessive quantifiers in Python regex to stop catastrophic backtracking on hostile input, and measure the difference against greedy groups.
Order scheduled jobs with queue.PriorityQueue and a sequence tiebreaker, so urgent work always dequeues first and equal priorities stay stable.
Fan out CPU-bound prime counting across a ProcessPoolExecutor, map inputs to workers, and keep the Windows-safe main guard.
Expose computed values as attributes with property, keeping validation and derivation inside the class instead of at call sites.
Schedule callbacks with sched.scheduler, order same-time events by priority, inspect the queue, and cancel an event before it runs.
Register sockets with selectors, wait for read and write readiness, and route events by key data without blocking a thread per connection.
Register SIGINT and SIGTERM handlers that flip a shutdown flag, letting the worker finish its current job before the process exits cleanly.
Register a Python aggregate with sqlite3 create_aggregate, implement step and finalize, and compute a per-group median in SQL.
Copy a live SQLite database with Connection.backup, stream pages, verify integrity, and compare the copied row count.
Return SQLite rows as mappings with row_factory, read columns by name, and switch to plain dict rows with a custom factory.
Build a statistics.NormalDist from mean and standard deviation, then read PDF, CDF, and inverse CDF values for a normal distribution.
Stage disposable files with tempfile: TemporaryDirectory cleans whole trees, NamedTemporaryFile reserves a name, and mkstemp hands over full control.
Submit many small jobs to a ThreadPoolExecutor and consume results as each future finishes, instead of blocking in submission order.
Derive every rich comparison from __eq__ and __lt__ with functools.total_ordering, so sorting, min, and max work without boilerplate.
Capture an exception with TracebackException, format its frames, and walk the explicit cause chain without printing to stderr.
Start tracemalloc, snapshot before and after building an index, compare allocation sites by line, and read current versus peak memory.
Declare typing.overload signatures for int and str inputs, keep one runtime implementation, and inspect the registered overloads.
Annotate fluent methods with typing.Self so subclasses keep their own return type, then chain configuration calls and build the final query.
Resolve relative links against a base URL with urllib.parse.urljoin, including query-only, fragment, and scheme-relative references.
Emit and capture warnings with warnings.catch_warnings, promote them to errors with a filter, and inspect the recorded category and message.
Register weakref.finalize callbacks so cleanup runs when an object is collected, without keeping the object alive or leaking resources.
Create, read, and verify a ZIP archive entirely in memory with zipfile and BytesIO, including member metadata and a corruption check.
Compress and decompress bytes with zlib, including incremental compressobj and decompressobj streams for chunked payloads.
Build and query dictionaries with get, setdefault, and comprehensions so grouping logic is one expression instead of nested branches.
Walk sequences with index and in parallel using enumerate and zip, replacing index arithmetic and off-by-one-prone range loops.
Design a small exception hierarchy so callers can catch broadly or precisely, and chain causes without losing the original traceback.
Sort anything with key functions — multi-field tuples, case-insensitive text, reverse runs — instead of comparison callback pyramids.
Render numbers, dates, and tables with f-string format specs — alignment, padding, and precision without printf-style confusion.
dataclass fields declare mutable defaults through field(default_factory=list), giving every instance a fresh list instead of one shared across all of them.
Deduplicate records by choosing a key function and relying on dict insertion order: first-wins and last-wins are both one pass with no aux dedupe type.
fnmatch.filter matches shell-style patterns against filename lists, and fnmatchcase opts out of the platform case-insensitivity that fnmatch applies.
Freeze lookup tables with frozenset: mutation fails loudly at the source, hashing lets sets key dicts and appear inside other sets, and algebra still works.
functools.wraps copies __name__ and __doc__ onto the wrapper, so decorated functions keep their identity in logs, tracebacks, and help output.
Extended unpacking assigns first, *middle, last in one statement, and the starred slot absorbs zero or more items, so it never raises on short sequences.
Render grouped currency and number strings with locale.currency and locale.format_string so separators come from the locale database, not string surgery.
os.path.splitext returns name and extension as a pair by splitting only the final dot, while basename and dirname carve up the path around it.
Build and join pure path objects over in-memory trees: PurePosixPath does string algebra with no filesystem access, so manifests and reports stay deterministic.
Turn HTTP Range headers into safe (start, end) slices: suffix and open-ended forms clamp to the body size, and malformed ranges resolve to None.
statistics.mean, median, mode, and multimode give four different centers for one skewed list, and the disagreement itself is the signal worth reading.
Add timedelta to aware datetimes across a DST switch: wall-clock arithmetic keeps 7 hours but the UTC span changes — the booking-code contract.
Enforce interface contracts with abc: abstract methods raise TypeError at instantiation time when a subclass leaves one unimplemented.
array.array stores numbers in raw machine width by typecode, enforces element types with TypeError, and converts through tobytes and frombytes.
operator.attrgetter builds attribute accessors, supports dotted paths and multiple names as tuple keys, and plugs directly into sorted, min and max.
urlsafe_b64encode with the '=' padding stripped produces JWT-style segments, and decode restores the missing padding before decoding.
hashlib.blake2b takes a key parameter, turning an ordinary digest into a keyed MAC whose digest_size you can shorten to fit tight headers.
bytes.decode picks an error strategy: strict raises UnicodeDecodeError, replace marks bad bytes, ignore drops them, backslashreplace keeps the evidence.
bytes.hex encodes binary as hex text with optional separators, and bytes.fromhex restores it, rejecting odd-length input instead of guessing.
calendar.isleap, monthrange, and monthdatescalendar answer leap-year, month-length, and grid questions with locale-aware weekday names in one import.
str.casefold folds locale-specific letters like German ß to their base form, so case-insensitive matching outlives what str.lower() gets wrong.
cmp_to_key wraps a two-element comparator for sorted when directions conflict, like ascending departments with a descending string field that cannot be negated.
Capture print output in tests by redirecting sys.stdout into a StringIO inside redirect_stdout; the with block restores the real stdout automatically.
contextlib.suppress swallows only the listed exception types while anything else still propagates, replacing bare except blocks with stated intent.
slots=True, frozen=True, and kw_only=True turn a dataclass into an immutable config record: keyword-only construction and no per-instance __dict__.
Produce updated frozen dataclass instances with dataclasses.replace: overridden keywords, untouched remainder, and a chain of traceable copies.
datetime.strptime maps format directives onto a fixed string layout and raises ValueError on any mismatch, giving strict parsing for inbound date fields.
Shift dates with timedelta instead of hand-rolled month tables: cross-month adds, multiplied buffers, and negative steps keep calendar semantics.
Assignment aliases and shallow copy shares nested containers; copy.deepcopy alone detaches every level so mutations stop leaking across names.
Swapping keys and values with a dict comprehension gives O(1) reverse lookups; duplicate values need setdefault grouping or the inversion loses rows.
The dict union operator merges flat keys with the right side winning, while nested dicts are replaced wholesale — deep merging still needs recursion.
Loop with index and item together using enumerate: start shifts the numbering for human ranks, and list materializes index-item tuples.
Render templates whose keys may be missing by pairing format_map with a __missing__ fallback instead of letting KeyError abort the whole render.
The = specifier prints each expression beside its repr for self-documenting debug output, and the !r !s !a conversions pick the shape before formatting.
re.fullmatch requires the pattern to cover the entire string; match and search only anchor the start, so trailing garbage slips past validation.
Cache expensive per-instance results with cached_property: the first access computes, later reads reuse the stored value without recomputation.
functools.partial binds leading positional and keyword arguments ahead of time, and the resulting object exposes func and keywords for introspection.
functools.reduce folds a binary function left to right; without an initializer empty sequences raise TypeError, with one the initial value is returned.
The graphlib module computes a dependency order and, with prepare plus get_ready, hands out batches of nodes that can run in parallel right now.
gzip.compress and gzip.decompress roundtrip bytes through the gzip container format: repeated payloads shrink and restore byte-for-byte.
heapq.merge k-way merges already-sorted iterables lazily, honoring reverse and key, so multiple ordered sources yield one ordered sequence.
heapq.nlargest and nsmallest return the top or bottom k items without sorting everything, the stdlib shortcut when k is small next to the collection length.
Push (priority, seq, task) tuples with heapq so equal priorities pop in insertion order and non-comparable task objects never enter the comparison.
Hold deferred callbacks in a min-heap keyed by monotonic deadlines: pop everything due now, then report the next task still waiting.
int.to_bytes serializes integers at a fixed width and byte order, from_bytes parses them back, and widths too small raise OverflowError instead of truncating.
isdigit accepts superscripts and other non-decimal digits, so input validation that feeds int() must gate on isdecimal instead of isdigit.
itertools.accumulate streams running totals, products, and maxima in one lazy pass, with an optional initial seed and any two-argument function.
chain and chain.from_iterable stream elements from several iterables lazily, flattening one nesting level without materializing intermediate lists.
Slice iterators lazily with islice: consecutive batches continue where the last slice stopped, while windows over a list leave the sequence untouched.
Turn a series into adjacent pairs with itertools.pairwise, then feed deltas, peak steps, tee branching, and starmap calls from those windows.
itertools.product expands several iterables into the cartesian product, combinations picks unordered subsets, permutations keeps order.
dropwhile skips a leading run that satisfies the predicate and takewhile keeps only that run; both stop at the first mismatch, unlike filter.
Keep uneven sequences aligned with zip_longest: fillvalue marks the missing side explicitly instead of letting zip truncate silently.
object_pairs_hook receives every JSON object as a list of pairs, so duplicate keys can be rejected or collected instead of silently overwriting.
types.MappingProxyType wraps a dict in a dynamic read-only view: reads stay live, writes raise TypeError, and frozenset values freeze the inner levels too.
Structural pattern matching unwraps dicts and sequences in one case ladder: literal keys bind capture variables and guards reject values the shape alone cannot.
math.fsum tracks every intermediate bit so the total matches exact decimal intent, while builtin sum accumulates binary float error on repeated additions.
math.gcd reduces ratios, math.lcm finds the shared cadence of periodic jobs, and math.prod multiplies a list without an explicit reduce loop.
math.sqrt converts to float first and loses precision past 2**53, while math.isqrt stays exact on arbitrarily large integers and detects perfect squares.
namedtuple turns plain tuples into records with named fields: _make builds from sequences, _replace copies with edits, _asdict exports a dict.
Track most-recently-used keys with OrderedDict: move_to_end on touch, popitem(last=False) evicts from the oldest end, iteration order stays observable.
pprint prints nested dicts and lists with stable indentation and line width, and pformat returns the same layout as a string for logs and golden assertions.
A @property setter turns ordinary assignment into a validation point, so out-of-range values are rejected even during construction.
queue.Queue moves tasks between threads without manual locks; task_done and join form a completion barrier, and a sentinel stops the worker.
random.Random(seed) produces the same draws, shuffles, and samples on every replay, so tests and demos stay reproducible; unseeded instances differ.
Scan a line into structured records with re.finditer: named groups, one-pass iterators that drain, and span positions for surgical edits.
Each lookahead assertion inspects one requirement without consuming characters, so a single combined pattern can enforce several password rules at once.
re.split returns capture groups alongside the fields, so delimiters stay in the result list and the original line can be rebuilt byte for byte with join.