atexit Registers Ordered Shutdown Hooks
Register atexit cleanup hooks, observe reverse execution order, unregister one callback, and keep shutdown work deterministic.
Page 22 of 50
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.
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.
Walk neighbor pairs with windows(2) and batch fixed groups with chunks, two complementary views over the same slice.
Downcast Box<dyn Any> values back to concrete types so heterogeneous registries stay type safe without enums or unsafe code.
Watch Arc::strong_count rise and fall as clones are created and dropped, and use Arc::ptr_eq to prove two handles share one allocation.
Give a trait an associated type so each implementation chooses its own output type, then constrain that output in generic functions.
Track a high water mark across threads with AtomicU64::fetch_max, reading the previous maximum on every update without taking a lock.
Read std::thread::available_parallelism, clamp it to a safe worker count, and run one job per worker with scoped threads.
Capture the current call stack with std::backtrace::Backtrace and inspect its frames to enrich error reports without extra crates.
Merge two BTreeMap values with append, watch duplicate keys take the incoming value, and confirm the source map becomes empty.
Partition a BTreeMap at a key with split_off, inspect both halves, and confirm the boundary key lands in the right-hand map.
Query BTreeSet ranges, neighbors, and extreme elements so sorted unique collections answer boundary questions without linear scans.
Resolve a path containing dot segments with fs::canonicalize, confirm it becomes absolute, and compare it with the original file.
Write chars into a fixed byte buffer with char::encode_utf8 and check that the returned length matches the UTF-8 width.
Parse user keystrokes with char::to_digit so each character is validated in radix before any arithmetic happens.
Wrap keys in std::cmp::Reverse to invert ordering, turning ascending sorts into descending ones and BinaryHeap into a min-heap.
Bound a condition wait with Condvar::wait_timeout_while so a missing notification becomes a deadline instead of a hung thread.
Bucket every character of a password candidate into digit, letter, whitespace, and symbol counts using char classification methods.
Resolve relative paths against env::current_dir so a tool finds the same files no matter which directory launched it.
Decode UTF-16 code units with char::decode_utf16, merging surrogate pairs and reporting unpaired surrogates without panicking.
Hash keys into shards with DefaultHasher for stable in-process bucketing, remembering that the output is not portable across releases.
Bind struct fields straight from match patterns with literals, @ bindings, and range checks, replacing field-by-field if chains.
Give state enums an explicit u8 backing with #[repr(u8)] so variants map to stable wire values and match stays exhaustive.
Read command line arguments from std::env::args, validate flags and values, and return process exit codes without any argument-parsing crate.
Duplicate a file handle with File::try_clone and observe that both handles advance one shared cursor instead of independent positions.
Round-trip floats through f64::to_bits and from_bits to preserve negative zero and NaN payloads that ordinary equality cannot check.
Compare floating point values with a relative tolerance plus an absolute fallback, because exact equality rarely survives arithmetic.
Create a hard link with fs::hard_link, confirm both paths share file data, then modify through one name and read the change.
Move every entry out of a HashMap with drain, filter owned pairs into a Vec, and verify the map is empty afterward.
Insert-or-update in one lookup with the entry API, avoiding double hashing and the borrow-checker workarounds of get-then-insert.
Compare naive squaring with f64::hypot on huge and tiny inputs to show how hypot avoids intermediate overflow and underflow.
Embed a text file into the binary with include_str so templates and manifests are available at runtime without filesystem reads.
Count set bits, measure leading zeros, and round up with next_power_of_two while walking u32 bit positions and rotates.
Concatenate readers with io::chain so headers, bodies, and multiple sources are consumed as one continuous byte stream.
Move bytes between readers and writers with io::copy, including an infinite repeat reader bounded by take and a discarding sink.
Push and pop at both ends of std::collections::LinkedList, then append, split, and iterate lists without contiguous memory.
Parse timestamped log lines with enumerate so every validation error reports the exact source line instead of a bare message.
Derive the shared prefix of string slices by zipping character iterators and cutting at the first mismatch, no extra allocation.
Implement Display and std::error::Error by hand for a config error enum, keeping dependencies off the table while messages stay precise.
Print std::mem sizes and alignments for primitives and a repr(C) struct to reason about padding, cache lines, and buffer layout.
Probe a held std::sync::Mutex with try_lock, match TryLockError::WouldBlock, then acquire it normally after the guard drops.
Order records with Ordering::then_with so the secondary comparison only runs when the primary keys tie, keeping expensive keys out of the hot path.
Match brackets with a Vec stack, pushing opens and popping closes, so mismatches report both the position and the expected closer.
Decompose slices with pattern matching and guards so list shapes like empty, single, and rest are handled without index gymnastics.
Call Rc::try_unwrap while other handles exist to see the error path, drop them, then reclaim the inner String without cloning.
Limit untrusted readers with Read::take so header reads and capped downloads never consume more bytes than the caller allows.
Split byte streams on a delimiter with BufRead::read_until, keeping the separator and handling a final chunk that lacks it.
Build Results with Ok and Err, lift fallible steps into one pipeline, and collect into Result<Vec, E> so any failure sinks the batch.
Propagate errors up the call stack with the ? operator, converting via From so each layer adds context without match boilerplate.