#python Clear
Tags #php #kotlin #bash #go #sql #rust #typescript #html #java #python #files #utils #strings #http #concurrency #async #json #arrays #security #types #crypto #database #dates #format
Python Run sync Iterables as async Stream
Wrap a blocking iterator so each yield happens in a worker thread — useful when integrating sync libraries (DB cursors, file iterators) into an async pipeline without rewriting them.
Python TypedDict for JSON API Shapes
When you parse JSON, you want types — but creating a class for every payload is overkill. TypedDict gives you the static-checking benefits without the runtime overhead, and `total=False` marks every field optional.
Python Timing Decorator with Logger
Drop @timed on any function and get its wall-clock duration logged on every call. Uses functools.wraps so introspection (name, docstring, signature) still works.
Python Sliding Window Iterator
Iterate over an iterable with a rolling window of N items. itertools.batched (Python 3.12+) gives you NON-overlapping chunks; this helper gives overlapping ones, common for moving averages or n-gram analysis.
Python take / drop / takewhile
Take the first N items of an iterable (or while a predicate holds). drop is the complement. Lazy via islice + itertools.dropwhile — works on infinite generators.
Python Async Retry with Exponential Backoff
Retry an async operation up to N times, doubling the wait each attempt with random jitter to avoid thundering herd. Predicate controls retryability so 4xx errors stop immediately.
Python Bulk Insert with executemany
Insert many rows in one round-trip using executemany. Orders-of-magnitude faster than a loop of single inserts — and the driver handles batching/parametrization for you.
Python requests Session with Retry + Timeouts
A pre-configured requests.Session that auto-retries 5xx + connect errors with exponential backoff, applies a default timeout, and uses connection pooling. Use this everywhere instead of bare requests.get().
Python group_by — Group Items by a Key
A dict-returning groupby that doesn't require sorted input. Like itertools.groupby but materializes the groups so consumers can iterate them multiple times.
Python flatten — Recursively Flatten Nested Lists
Yield every leaf from arbitrarily-nested lists/tuples. Strings are intentionally treated as atomic (we don't want to "flatten" "hi" into ["h", "i"]).
Python Safe JSON Read/Write
Idiomatic helpers for reading + writing JSON to disk, with atomic writes and pretty-printed output. Catches the common "edit and save → corrupt file on crash" failure mode.
Python NewType for Nominal IDs
Python's type system is structural — `UserId` and `PostId` are both just `int` unless you ask otherwise. `NewType` creates a distinct type with zero runtime cost for static checking only.
Python Generate Strong Random Password
Build a password using the `secrets` module (CSPRNG) with rejection sampling for unbiased distribution. Use this — NOT random.choice, which is seeded predictably.
Python Stream-Download Large File with Progress
Download a file in chunks so memory stays flat regardless of file size, with a tqdm progress bar showing speed + ETA. Skips re-download if the file is already complete.
Python JWT Sign + Verify (PyJWT)
The de-facto JWT library for Python. HS256 demo with an exp claim and the standard "verify everything" decode flow. Mind that PyJWT raises specific exceptions you can catch separately.
Python Async Context Manager (aiohttp pattern)
Define an async resource using `@asynccontextmanager` from contextlib. Cleaner than writing a class with __aenter__/__aexit__ for one-off wrappers.
Python unique_everseen — Order-Preserving Dedupe
Remove duplicates while preserving original order (set() loses order on collisions). Optional key function lets you dedupe by a derived value — e.g., lowercased email.
Python Stream Large CSV with DictReader
Iterate over a CSV row-by-row as a dict — never loading the whole file. Tolerant of UTF-8 BOMs (utf-8-sig). Generator wrapper makes consumers naturally use for/break.