Dev Helpers

Developer journal

Python

Practical notes on iterators, dictionaries, data processing and the standard library.

← All categories

Python

Run an async function

An async function call creates a coroutine. A top-level runner supplies the event loop that executes it.

Transpose a matrix

Transposing rows into columns assumes a decision about uneven rows. Ordinary zip stops at the shortest input.

Unpack with a remainder

Starred unpacking separates a fixed header from a variable-length tail. It still requires enough elements for the fixed positions.

Use quotient and remainder

A page number and offset are the quotient and remainder of the same division. divmod returns both from one operation.

Pad an identifier

Padding belongs to the display form of an identifier. Keeping IDs as strings preserves meaningful leading zeroes.

Check expected values with assertions

Assertions make assumptions visible in tests. Python can disable them in optimized execution, so required input validation deserves an explicit exception.

Read multiple suffixes of an archive

A compound extension such as .tar.gz describes more than a final suffix. pathlib exposes the suffix list without manual string slicing.

Find a symmetric difference

A symmetric difference contains values found on exactly one side. It works well for comparing membership snapshots where multiplicity is irrelevant.

Catch a timeout around a task

A timeout limits how long a caller waits and can cancel work inside its scope. Cleanup needs to survive cancellation.

Find the three largest values

When a dashboard needs only a few leaders, a top-k operation avoids constructing a complete sorted report. Keep the desired output order explicit.

Flatten one level

A one-level flatten turns a sequence of groups into a sequence of members. Deeper lists remain members in their own right.

Read the most common element

A frequency table preserves counts that a set would lose. Counter can return ranked entries without a custom counting loop.

Compute an integer square root

Integer square roots avoid rounding a large count through a floating-point value. The result is the largest integer whose square fits.

Enumerate from one

Human-facing row numbers often start at one while sequence indexes start at zero. enumerate accepts a display offset directly.

Encode sorted JSON

Sorting JSON keys makes snapshots easier to compare. Array order remains significant and is preserved.

Remove duplicates in order

An ordered dictionary of keys provides a compact way to deduplicate hashable values in first-seen order.

Use positional-only parameters

A positional-only parameter lets a library change its internal argument name without breaking keyword callers. The slash marks the boundary.

Get month length

Month length depends on both the month and the year. Ask the calendar rather than maintaining a table with a special February branch.

Define a dataclass

A dataclass defines the shape of a small record while generating routine initialization and representation methods.

Read an ISO week date

ISO week numbering has its own year boundary. A late-December calendar date can belong to week one of the next ISO year.

Format bytes using hexadecimal

Hexadecimal represents each byte with two digits. It is a convenient inspection format for payloads that are awkward to print.

Chunk a list

Chunk boundaries are easier to inspect when the final short chunk remains intact. Slices naturally stop at the end of the list.

Chain multiple iterables

Chaining iterables lets a consumer traverse several sources through one iterator. It does not need a combined intermediate list.

Join path segments

Path objects join segments according to filesystem rules. An absolute later segment can replace the earlier base.

Split on multiple delimiters

A regular expression can describe a family of separators in one pass. Consecutive separators raise a separate question about empty fields.

Merge sorted streams lazily

A lazy merge can yield the next smallest item across sorted inputs. Its ordering guarantee depends on each input already being sorted.

Replace every other list item

Extended slice assignment edits selected positions in place. With a stride other than one, the replacement length must match the selected positions.