Practical developer notes.
Python, CSV, SQLite and local tooling. Concrete examples, official sources and clear limits.
- Write Deterministic JSON for Local CLI Reports
Write Deterministic JSON for Local CLI Reports
- Compare Two Text Files in Python Without Modifying Them
Compare Two Text Files in Python Without Modifying Them
- Seven CSV Quality Checks to Run Before Importing Data
Seven CSV Quality Checks to Run Before Importing Data
- Detect duplicate CSV headers before mapping fields
Practical Python guidance: detect duplicate csv headers before mapping fields.
- Treat whitespace-only CSV values as missing without rewriting data
Practical Python guidance: treat whitespace-only csv values as missing without rewriting data.
- Explain ragged CSV rows with record-level evidence
Practical Python guidance: explain ragged csv rows with record-level evidence.
- Choose a composite CSV key when one identifier is not unique
Practical Python guidance: choose a composite csv key when one identifier is not unique.
- Handle blank components in a CSV duplicate key
Practical Python guidance: handle blank components in a csv duplicate key.
- Validate a UTF-8 CSV with a byte-order mark
Practical Python guidance: validate a utf-8 csv with a byte-order mark.
- Design an encoding-failure report that a shell script can use
Practical Python guidance: design an encoding-failure report that a shell script can use.
- Use newline handling correctly with Python csv readers
Practical Python guidance: use newline handling correctly with python csv readers.
- Constrain delimiter detection instead of trusting a heuristic
Practical Python guidance: constrain delimiter detection instead of trusting a heuristic.
- Detect an unexpected CSV column without rejecting useful exports
Practical Python guidance: detect an unexpected csv column without rejecting useful exports.
- Preserve leading-zero identifiers during CSV preflight
Practical Python guidance: preserve leading-zero identifiers during csv preflight.
- Distinguish empty strings from missing CSV columns
Practical Python guidance: distinguish empty strings from missing csv columns.
- Check whether CSV header normalization creates a collision
Practical Python guidance: check whether csv header normalization creates a collision.
- Report duplicate rows without exposing the whole row
Practical Python guidance: report duplicate rows without exposing the whole row.
- Keep JSON CSV reports from overwriting an existing file
Practical Python guidance: keep json csv reports from overwriting an existing file.
- Test CSV report output against symlink and hardlink aliases
Practical Python guidance: test csv report output against symlink and hardlink aliases.
- Return clear exit statuses from a CSV preflight check
Use CSV parsing to return stable clean, finding, and input-error statuses from a local preflight command.
- Set a field-size policy for unusually large CSV cells
Practical Python guidance: set a field-size policy for unusually large csv cells.
- Explain strict CSV parsing as a choice, not a repair
Practical Python guidance: explain strict csv parsing as a choice, not a repair.
- Count CSV records when quoted fields span physical lines
Practical Python guidance: count csv records when quoted fields span physical lines.
- Create a CSV required-column contract for a one-off import
Practical Python guidance: create a csv required-column contract for a one-off import.
- Validate decimal-looking CSV fields without changing them
Practical Python guidance: validate decimal-looking csv fields without changing them.
- Compare two CSV header shapes before an import migration
Practical Python guidance: compare two csv header shapes before an import migration.
- Keep comment-like rows out of a CSV contract discussion
Practical Python guidance: keep comment-like rows out of a csv contract discussion.
- Explain why CSV null round-trips can lose meaning
Practical Python guidance: explain why csv null round-trips can lose meaning.
- Choose pathlib lexical paths versus resolved paths in a local tool
Practical Python guidance: choose pathlib lexical paths versus resolved paths in a local tool.
- Create a new local report without replacing an existing file
Practical Python guidance: create a new local report without replacing an existing file.
- Return a readable CLI error when a report parent directory is missing
Practical Python guidance: return a readable cli error when a report parent directory is missing.
- Use bytes assertions to prove a read-only input stayed unchanged
Practical Python guidance: use bytes assertions to prove a read-only input stayed unchanged.
- Decide when to read a local file as bytes instead of text
Practical Python guidance: decide when to read a local file as bytes instead of text.
- Explain JSON decode errors as input findings
Practical Python guidance: explain json decode errors as input findings.
- Make argparse exit behavior testable
Practical Python guidance: make argparse exit behavior testable.
- Separate stdout data from stderr diagnostics in a CLI
Practical Python guidance: separate stdout data from stderr diagnostics in a cli.
- Use temporary directories for filesystem tests
A filesystem test needs a directory it owns. `TemporaryDirectory` creates that directory and removes it when the `with` block finishes, including when an assertion raises. Construc
- Limit local file reads before parsing a manifest
Checking `Path.stat().st_size` before parsing can reject an obviously oversized manifest without loading its contents. Here the fixture contains 33 bytes and the demonstration limi
- Walk a project tree without following directory symlinks
`os.walk(root, followlinks=False)` avoids descending through directory symlinks. The example also removes symlink entries from the mutable directory list before descent, making its
- Design ignore lists for local project scans
To exclude generated directories with `os.walk`, edit the supplied directory list in place before the next iteration. The slice assignment changes the list that the walker will con
- Keep absolute machine paths out of shareable reports
A shareable report rarely needs the absolute directory where a project happened to be checked out. `Path.relative_to(root)` expresses a discovered path using the selected project r
- Normalize line endings in a generated text artifact
For a generated artifact with an explicit LF convention, writing bytes avoids platform-dependent text newline translation. The byte literal in this example contains two lines, each
- Handle an unknown text encoding name without a Python traceback
Validate a requested text encoding before attempting to decode input. `codecs.lookup` resolves a registered encoding name and raises `LookupError` when that name is unknown. Catchi
- Treat Unicode normalization in filenames as a portability concern
Two filenames can look alike while their Unicode strings differ. The example compares a precomposed accented character with an equivalent sequence containing a combining accent. Th
- Use a TOML parser only for supported manifest fields
tomllib.loads answers whether text is syntactically TOML and returns nested Python mappings. It does not decide whether a product supports project.name. The script reads
- Build a safe ZIP allowlist for a downloadable product
writestr creates the named archive member directly. Reopening the finished ZIP and comparing namelist checks the central-directory result, not just the code’s intended wr
- Inspect a ZIP before delivery without extracting it over a workspace
namelist lists recorded members and read returns bytes for a selected member. The example checks both while the ZipFile is open and never calls extract, so no archive mem
- Reject archive entries that would escape an extraction folder
The candidate target is formed below the extraction root and resolved before any write. relative_to accepts it only when it remains under that root; a parent-path candida
- Use content hashes to identify a reviewed downloadable artifact
sha256 consumes the temporary artifact bytes, and hexdigest exposes a 64-character hexadecimal digest. The script checks that full width while printing a shorter display
- Design a file-processing CLI around explicit modes
add_subparsers stores the chosen command in mode, and required=True makes no-mode invocations argparse usage errors. add_parser registers inspect, so the explicit argv pr
- Explain why a report cannot guarantee privacy
The dictionary deliberately contains Path.name and a calculated line count. It omits temporary parent paths and the source text itself, which makes the exact report schem
- Test filesystem failure paths without changing permissions
Path.write_text tries to open its target for text output. A directory made in TemporaryDirectory supplies a controlled failure without changing permissions or touching a
- Choose a stable error vocabulary for a local CLI
Path.exists observes the synthetic candidate before processing. The false result becomes the fixed token missing-input, so an automation client can react to a documented
- Choose a request key before adding a SQLite uniqueness constraint
UNIQUE(owner, request_key) makes the pair the queue identity. The repeated pair raises IntegrityError and the count remains one, while a different owner could use the sam
- Use SQLite UPSERT to make enqueue retries explicit
The first execution inserts r1 with zero retries. The second conflicts on request_key and executes DO UPDATE, which increments retries. Because payload is not named in th
- Explain why a claimed queue job is not a completed job
The conditional UPDATE changes queued to claimed, and commit persists that state. The assertions then show claimed and not completed because no completion operation appea
- Add a lease-expiry field to a SQLite job record
The UPDATE requires claimed state and lease_until less than synthetic now, so the row at 100 returns to queued at 101. rowcount and the SELECT confirm one conditional rec
- Use placeholders for SQLite queue inputs
The question mark is a placeholder and (key,) is a one-item parameter tuple. The apostrophe and semicolon in the request key round-trip unchanged because Connection.execu
- Compare BEGIN modes for a local SQLite worker design
The script opens DEFERRED and IMMEDIATE transactions and checks in_transaction. Deferred waits for the first write to seek write access; IMMEDIATE seeks it at BEGIN, whic
- Handle SQLite busy errors without claiming infinite retries are safe
The first connection takes an exclusive transaction. The second uses timeout=0, so its INSERT immediately raises OperationalError when locked. finally rolls back and clos
- Keep a queue claim selection and update in one transaction
BEGIN IMMEDIATE starts the local write transaction before the oldest queued id is selected. The UPDATE repeats state = queued while setting that id to claimed, and rowcou
- Use a CHECK constraint for allowed SQLite queue states
The CHECK expression allows queued, claimed, and done; invented raises IntegrityError while the valid row remains. Pair CHECK with NOT NULL when every row must hold one l
- Add a foreign key to associate a queue job with an owner record
REFERENCES owner(id) describes the relation, while PRAGMA foreign_keys = ON enables its enforcement on this connection. The missing owner is rejected; after owner 1 exist
- Store queue payload references instead of oversized payload blobs
payload_ref holds a synthetic object-style locator rather than a document body. The bound value round-trips by job id and is short in this fixture, making the indirection
- Create an index for the exact SQLite queue claim query
The index puts state first for the equality predicate and created second for the queue ordering. PRAGMA index_info returns indexed columns in sequence, so the script veri
- Use deterministic ordering when selecting the next queued job
ORDER BY priority, created, id defines the choice. The rows make id 4 lose priority, id 2 lose creation time, and id 3 lose the final id tie to id 1. LIMIT 1 is therefore
- Design SQLite queue timestamps with an explicit clock rule
The aware datetime uses timezone.utc and isoformat renders +00:00. The script writes that exact TEXT value through a SQLite placeholder and reads it back, making the crea
- Record a retry count without turning every error into a retry
The statement increments retries only for rows that are failed and retryable. rowcount is one, and the final rows show the permanent failure stayed unchanged. Classificat
- Use a savepoint for one optional local queue side effect
The outer transaction contains the job insert. SAVEPOINT surrounds the audit insert; ROLLBACK TO removes that row, RELEASE removes the marker, and outer commit persists t
- Run PRAGMA integrity_check as local maintenance evidence
Use PRAGMA integrity_check on a disposable SQLite file and report its single result without treating it as application validation.
- Choose WAL mode only after testing the local workload
Set journal_mode=WAL on a disposable database, verify SQLite accepted it, and treat the result as a local configuration observation.
- Make SQLite connection cleanup reliable in a worker helper
Close a SQLite connection in finally and use the connection context manager to roll back a failed unit of work.
- Store a last-error summary without storing sensitive payloads
Redact a known token-shaped fragment before storing a bounded SQLite error summary.
- Build a queue schema version table for local migrations
Store a schema version in its own table and reject a migration whose starting version is not the one it expects.
- Test duplicate enqueue behavior with a temporary SQLite database
Demonstrate that a UNIQUE queue key rejects the second enqueue and leaves one durable row.
- Use row_factory for readable SQLite inspection output
Set sqlite3.Row at the read boundary so a diagnostic can use column names and still assert the exact selected values.
- Explain why SQLite transactions cannot make an HTTP call atomic
Record an outbox row in a SQLite transaction and show why a later network action remains a separate failure boundary.
- Choose between soft delete and terminal queue states
Represent a completed queue record with an explicit terminal state and compare it with a separate soft-delete flag.
- Explain a filename hygiene score without calling it release approval
Score explicit filename signals and print the missing signals separately.
- Check for a root README without counting vendored documentation
Inspect only the requested root path for README.md, leaving nested vendor documentation out of the signal.
- Treat a license filename as a signal, not legal advice
Report the presence of a top-level LICENSE file without parsing its text or inferring legal suitability.
- Recognize test filename signals without running tests
Find declared test naming patterns in a synthetic tree while making no execution claim.
- Find a version in pyproject.toml without parsing every tool config
Read only [project].version, reporting dynamic and malformed metadata as unavailable.
- Read top-level package.json version metadata defensively
Parse only a string top-level version and distinguish wrong type from malformed JSON.
- Flag environment-named files without reading their values
Report environment-like filenames without reading their values.
- Ignore .env.example while warning on .env.production
Apply an explicit filename exception so a template is not reported as an active environment file.
- Keep a local project scan inside its intended directory tree
Skip symbolic links while scanning a temporary project root so an entry cannot redirect traversal outside the intended tree.
- Exclude dependency and build folders from a hygiene scan
Use a small named ignored-directory set so generated and dependency paths do not dominate a filename scan.
- Report incomplete filesystem traversal without revealing private paths
Publish an error count and completeness flag when one synthetic traversal result cannot be inspected.
- Format a hygiene report for Markdown review
Render IDs, statuses, details, and limits as separate Markdown fields.
- Use JSON hygiene reports in local automation without overclaiming
Serialize observations without encoding a release decision into the report.
- Choose stable check identifiers for a local reporting tool
Separate immutable check IDs from labels that can change for readers.
- Keep report output explicit in a read-only project scanner
Write output outside the scanned project so a report cannot become its own input.
- Explain what a release checklist cannot learn from filenames
Report checked filename signals and named unexamined areas side by side.
- Build a sample project that demonstrates every readiness signal
Create a disposable tree containing the exact filenames a scanner is documented to recognize.
- Test that environment-file values stay out of scanner reports
Use a synthetic sentinel to test that a filename report does not expose an environment-file value.
- Handle invalid TOML in a readiness scan
Catch TOMLDecodeError and report unavailable metadata instead of deriving a version from broken text.
- Decide whether a missing README is a warning or a hard gate
Keep a missing README finding separate from the policy that maps it to warning or block.
- Make a local CLI’s supported file-name conventions visible
Expose the exact test filename patterns a scanner supports and reject an unsupported near-match.
- Avoid scanning hidden dependency folders by accident
Filter exact hidden dependency directory components before reporting source paths.
- Reconcile two inventory counts with Counter subtraction
Compare physical and ledger inventory counts with positive-only Counter subtraction.
- Keep the latest fixed-size sensor window with deque
Retain only the newest sensor readings using a bounded deque.
- Rotate an on-call sequence without rebuilding a list
Advance an on-call rotation in place with deque.rotate().
- Group event labels with defaultdict
Accumulate repeated event labels by event ID with defaultdict(list).
- Layer request defaults with ChainMap
Resolve request, service, and baseline settings with explicit ChainMap precedence.
- Represent a compact measurement row with namedtuple
Create a small immutable measurement row with readable field access using collections.namedtuple.
- Move a recently used key to the end of OrderedDict
Refresh a present key's recency and evict the least-recent key with OrderedDict methods.
- Reject invalid updates in a small UserDict wrapper
Validate keys and bounded integer values in a small collections.UserDict subclass.
- Build an inverse index from tags with defaultdict
Turn item-to-tags data into a tag-to-items inverse index with defaultdict(list).
- Find the most common validation failures with Counter
Count validation error codes and rank the leading categories with collections.Counter.
- Consume a queue from both ends with deque
Use deque to take work from either the left or right end without list front-pop costs.
- Preserve insertion order while counting first appearances
Count hashable events with Counter while retaining the order in which distinct values first occur.
- Merge a local override into nested configuration lookups
Layer a local mapping over environment and default mappings with ChainMap.
- Make an immutable coordinate record with namedtuple
Create a compact coordinate type with named fields and functional updates using namedtuple.
- Remove zero and negative counts after a Counter update
Normalize a Counter after a signed update by applying unary plus.
- Use deque maxlen to retain recent status changes
Keep a bounded, chronological record of distinct status transitions with collections.deque.
- Generate pairwise changes from a sequence
Use itertools.pairwise to compare each sequence value with its immediate predecessor.
- Split an iterator into fixed-size batches
Consume an iterator lazily in fixed maximum-size tuples using itertools.islice.
- Filter repeated values while retaining first order
Remove later duplicates with a set while preserving the order of each first occurrence.
- Attach positions to values with enumerate
Add human-facing positions to iterable values with enumerate and a chosen start value.
- Zip parallel labels and values with strict length checking
Build a configuration mapping while rejecting unequal label and value streams.
- Sort records by two fields with operator.itemgetter
Order dictionary records by severity and then opening sequence using itemgetter.
- Group category records after sorting them
Make category groups contiguous before grouping them with itertools.groupby.
- Flatten one level of nested results with chain.from_iterable
Concatenate outer result collections without recursively flattening their records.
- Repeat a fixed schedule pattern with cycle
Generate a bounded sequence from a repeating fixed schedule with itertools.cycle.
- Bind a stable unit conversion with functools.partial
Bind source and destination units once to create a focused metres-to-centimetres converter.
- Cache a pure Fibonacci helper with lru_cache
Memoize a deterministic Fibonacci function with a bounded LRU cache.
- Use reduce to combine permission flags
Fold IntFlag permission selections into one bit mask with functools.reduce.
- Normalize mixed numeric inputs with singledispatch
Use singledispatch to normalize Decimal, int, and float inputs to finite two-decimal amounts.
- Keep decorator metadata with functools.wraps
Preserve useful function metadata when a logging decorator returns a wrapper.
- Sort version-like tuples with cmp_to_key
Use functools.cmp_to_key to sort dotted numeric version-like strings while treating missing trailing components as zero.
- Create a total ordering from equality and one comparison
Define equality and less-than once, then use functools.total_ordering to supply the remaining rich comparisons.
- Memoize an expensive pure lookup with cache
Use functools.cache to avoid repeating an unchanged catalog lookup for the same hashable SKU.
- Build a keyed formatter with partial
Freeze a format template with functools.partial and fill its named fields later with str.format_map.
- Fold a list of small mappings without mutation
Reduce small configuration layers with dict union, producing a new mapping without changing any input layer.
- Use reduce with an explicit identity for an empty input
Use functools.reduce with an explicit identity so an aggregation also handles an empty iterable.
- Dispatch a formatter for text and integer values
Register separate singledispatch implementations for str and int formatting while retaining a useful default error.
- Clear an lru_cache when its source rule changes
Call cache_clear after changing mutable rule data so lru_cache does not retain values computed under the old rule.
- Limit an lru_cache for bounded input varieties
Set a finite lru_cache maxsize and observe least-recently-used eviction with a small set of input keys.
- Compare records with a locale-independent comparison key
Use Unicode casefold and a tuple key to sort text records deterministically without changing process locale.
- Write a timing decorator that preserves a function name
A deterministic timing decorator that retains a decorated function's metadata.
- Compose two pure transformations explicitly
Build a small composition function and make transformation order visible.
- Use partialmethod for a fixed validation mode
Expose clear validation methods by binding a positional validation mode with partialmethod.
- Avoid caching a function that receives mutable input
Keep a list-taking boundary uncached and memoize an immutable snapshot privately.
- Make an immutable configuration key for caching
Use a frozen dataclass and normalized nested values as a reliable cache key.
- Use cached_property only for stable instance state
Cache a derived value only when the instance data it depends on remains stable.
- Sort null-like values last with a key function
Use a tuple key to order numbers first and a chosen missing-value marker last.
- Turn a binary predicate into a reusable filter
Bind one side of operator.le with partial to create a one-argument filter predicate.
- Use reduce to compute a checksum modulo a base
Accumulate byte values modulo a base with functools.reduce and an explicit initial value.
- Design a pure normalization pipeline for display labels
Compose Unicode normalization, whitespace cleanup, and display casing without mutating the input.
- Create a frozen dataclass snapshot for a price quote
Model a price quote as a frozen dataclass and handle attempted field reassignment.
- Use dataclass defaults safely with default_factory
Give every dataclass instance its own mutable list and dictionary defaults.
- Compare dataclass records by declared fields
Use generated dataclass equality to compare records with matching declared values.
- Replace one field in an immutable dataclass
Create a revised frozen dataclass value with dataclasses.replace().
- Store derived display data outside dataclass equality
Exclude a presentation-only dataclass field from generated equality with compare=False.
- Use slots for many small dataclass instances
Use dataclass slots to avoid per-instance attribute dictionaries when an object's attributes are fixed.
- Validate constructor input with __post_init__
Use a dataclass post-initialization hook to reject invalid constructor values.
- Pass setup-only input through InitVar
Use InitVar to accept constructor-only data without storing it as a dataclass field.
- Parse a string into an enum member deliberately
Choose enum-name lookup when external input is intended to name an enum member.
- Serialize enum names instead of implementation values
Store an enum member's name in JSON when the external format is defined around stable names.
- Use IntFlag to combine small capability bits
Represent independent, small capabilities as named integer flags and combine them with bitwise OR.
- Reject unknown flag bits at a runtime boundary
Validate an incoming integer mask before converting it to an IntFlag value.
- Make a stable public state enum
Use explicit string values for public state tokens and parse them with Enum value lookup.
- Use Enum membership rules without coercing arbitrary input
Guard Enum membership checks with an instance check when input may be arbitrary objects.
- Check a mapping shape before treating it as TypedDict-like
Validate mapping keys and runtime value types before using incoming data as a TypedDict-shaped record.
- Use isinstance only with runtime-checkable Protocols
Use a runtime-checkable Protocol for a narrow structural check, while understanding its limits.
- Write a TypeGuard for a two-item coordinate
Validate an unknown value as a two-float coordinate with TypeGuard.
- Validate optional JSON-like fields at the boundary
Convert JSON input into a validated internal settings dictionary at one boundary.
- Model a tagged result with dataclasses
Represent successful and failed parsing outcomes as separate dataclasses.
- Use kw_only dataclass fields to prevent argument swaps
Make similar dataclass parameters keyword-only so call sites name their meaning.
- Prevent a mutable default list in a dataclass
Create a fresh list per dataclass instance with field(default_factory=list).
- Choose repr=False for a non-display field
Exclude a non-display dataclass field from the generated representation without removing the field itself.
- Use dataclass field metadata for labels only
Store presentation labels in dataclass metadata and retrieve them through fields().
- Convert a dataclass to a dict without assuming deep validation
Use dataclasses.asdict() for recursive conversion, while keeping validation as a separate concern.
- Use a literal-like enum to make command states explicit
Use StrEnum to name a small set of string command states while retaining string values.
- Add currency amounts with Decimal instead of binary floats
Use Decimal values constructed from strings to add currency-like amounts exactly.
- Quantize a Decimal amount to two minor units
Round a Decimal amount to two places with an explicitly selected rounding mode.
- Split a Decimal total with an explicit remainder rule
Allocate a Decimal total in minor units and assign the leftover unit by a documented rule.
- Compare rational recipe ratios with Fraction
Compare recipe proportions exactly with Fraction instead of rounded decimal approximations.
- Reduce a Fraction after multiplying portions
Multiply recipe portions with Fraction and use its normalized result.
- Use math.isclose for a tolerance-based measurement check
Compare a measured length with its target using an explicit absolute tolerance.
- Use math.fsum for a more accurate float total
Preserve a small contribution in a floating-point total with math.fsum.
- Find a common batch size with gcd
Use math.gcd to calculate the largest equal batch size for several integer counts.
- Find a repeating schedule interval with lcm
Calculate when integer-minute recurring jobs next align with math.lcm.
- Use median to summarize skewed durations
Summarize typical request duration with statistics.median when one run is unusually slow.
- Use median_low for a discrete middle choice
Select the lower actual observation from an even-sized discrete ranking.
- Report the mode only when it is unique
Avoid presenting a tie as a single most-common category.
- Compute sample variance for a small measurement set
Calculate Bessel-corrected variance from a small sample using exact fractions.
- Distinguish population and sample standard deviation
Choose the standard-deviation denominator that matches whether data is a population or sample.
- Build every two-person review pair with combinations
Generate unordered reviewer pairs without self-pairs or reversed duplicates.
- Generate ordered assignment options with permutations
Use itertools.permutations to list distinct ordered assignments from a small pool.
- Enumerate a small option grid with product
Use itertools.product to enumerate every choice in a compact configuration grid.
- Count combinations before materializing them
Use math.comb to calculate a combination count before building tuple results.
- Use combinations_with_replacement for menu bundles
Model unordered menu bundles that may include repeated items with combinations_with_replacement.
- Generate a running total with accumulate
Use itertools.accumulate to turn a sequence of changes into deterministic running totals.
- Clamp a numeric input to a chosen interval
Use max() and min() to keep a numeric value within inclusive bounds.
- Convert degrees to radians for a math API
Convert a degree measurement with math.radians() before calling a trigonometric function.
- Use integer square root for a capacity estimate
Use math.isqrt() to find the largest square capacity that fits an integer budget.
- Check finite numeric input before processing
Reject NaN and infinities with math.isfinite() before a numeric calculation.
- Compute a weighted mean without losing its denominator
Divide the weighted total by the sum of weights, not by the number of values.
- Convert a UTC timestamp to a named time zone
Convert an aware UTC datetime to a named IANA time zone with zoneinfo.
- Keep an instant in UTC while displaying local time
Store an aware UTC instant and derive a viewer-specific local display value.
- Parse an ISO 8601 date before a calendar calculation
Parse an ISO 8601 date string before using its year and month in calendar functions.
- Find the first and last day of a month
Use calendar.monthrange to construct deterministic first and last date objects.
- Generate a Monday-first month grid with calendar
Build and print a Monday-first month grid using calendar.Calendar.
- Compare aware datetimes only after choosing time zones
Convert aware datetimes to UTC before comparing their instants.
- Represent a date-only deadline without a time component
Model a calendar deadline with datetime.date instead of an invented midnight.
- Add business days while skipping weekends
Count weekdays while advancing dates one calendar day at a time.
- Find the next weekday from a given date
Calculate the strictly next requested weekday with modular arithmetic.
- Group timestamps by calendar day in UTC
Normalize aware timestamps to UTC, then use their dates as grouping keys.
- Format a duration without calling it a wall-clock time
Format a timedelta as an elapsed duration with explicit sign and total hours.
- Use timedelta floor division for whole intervals
Count complete 15-minute intervals and retain an exact timedelta remainder.
- Detect an invalid calendar date from user text
Use date.fromisoformat and ValueError to distinguish valid and impossible ISO calendar dates.
- Explain DST fold ambiguity with two explicit instants
Convert two UTC instants to the repeated local hour and inspect the fold attribute.
- Avoid assuming every local wall time exists
Round-trip a local candidate through UTC to detect a daylight-saving gap.
- Build a rolling seven-day date range
Create an inclusive seven-day reporting window ending on a supplied date.
- Calculate age on a date without day-count shortcuts
Calculate completed calendar years while handling a stated leap-day birthday policy.
- Find an ISO week label for a reporting date
Format a reporting date using its ISO week-year and week number.
- Convert a year and week back to its Monday
Reconstruct the Monday of a valid ISO year and week.
- Normalize a list of dict records by selected keys
Project dictionary records into a consistent selected-key shape with explicit missing values.
- Transpose a small rectangular matrix with zip strict
Use zip(..., strict=True) to transpose a validated small rectangular matrix.
- Merge two sorted number streams deterministically
Merge ascending numeric iterables with heapq.merge without sorting their combined contents.
- Partition records into accepted and rejected lists
Classify ordered score records into two lists with an explicit threshold.
- Flatten nested batches while preserving order
Flatten one level of batches in encounter order with itertools.chain.from_iterable.
- Create deterministic unique labels with suffixes
Create globally unique labels in encounter order, adding numeric suffixes while avoiding pre-existing suffix-shaped names.
- Reject a path that escapes a temporary workspace
Resolve a candidate path and require it to be relative to the resolved temporary workspace.
- List only direct report files by suffix
Use iterdir, is_file, and suffix to select direct CSV report files without descending into subdirectories.
- Replace the final suffix of a generated report
Use Path.with_suffix to derive a JSON report name from a text report while preserving earlier dots.
- Preserve a double suffix while naming an archive
Use suffixes and removesuffix to insert an archive label before a compound .tar.gz suffix.
- Create a missing nested output directory
Create all absent output-directory parents with Path.mkdir(parents=True, exist_ok=True).
- Write a UTF-8 manifest into a temporary folder
Write a compact UTF-8 JSON manifest in an automatically cleaned temporary directory.
- Read a small text fixture with an explicit encoding
Decode controlled UTF-8 fixture bytes with an explicit encoding.
- Find a relative path below a known root
Derive a project-relative descendant path with Path.relative_to.
- Sort temporary report paths by filename
Sort Path objects by their final filename for a deterministic report order.
- Detect a directory where a file is required
Distinguish a directory from a required regular-file path with pathlib checks.
- Build a platform-neutral cache path
Construct equivalent cache keys for POSIX and Windows path flavours without filesystem access.
- Use PurePosixPath to inspect an archive member
Inspect a slash-delimited archive member name lexically with PurePosixPath.
- Keep a source fixture and derived file separate
Use distinct paths for fixture input and generated output inside a temporary workspace.
- Create a unique temporary work directory
Use TemporaryDirectory as an isolated work area with automatic cleanup.
- Write an atomic-looking staging file within one directory
Stage replacement content beside its target, then commit it with Path.replace.
- Archive two generated text members with zipfile
Create a temporary ZIP containing two generated UTF-8 text members and verify their contents.
- List ZIP member names without extracting
Read and print ZIP member names from central-directory metadata without extracting files.
- Reject unsafe ZIP member names before extraction
Apply a conservative member-name policy before any ZIP extraction is attempted.
- Verify a ZIP archive with testzip
Check every member of a temporary ZIP archive with ZipFile.testzip.
- Read one ZIP member as text
Open a selected ZIP member as bytes, decode UTF-8, and print the exact text.
- Round-trip a gzip-compressed text fixture
Compress and restore a UTF-8 text fixture entirely in memory with gzip.
- Round-trip a bz2-compressed text fixture
Create a bzip2 text fixture in memory and verify its restored content.
- Round-trip an lzma-compressed text fixture
Use an in-memory XZ fixture and verify its LZMA decompression result.
- Limit an in-memory tar member name to a safe relative path
Validate a portable relative tar member name before adding an in-memory file.
- Compare compressed bytes only after decompression
Demonstrate content comparison for gzip streams with different encoded bytes.
- Parse a required local input name with argparse
Define a required positional local input name and read it from argparse's Namespace.
- Use argparse choices for a report format
Constrain a report format option to text or json with argparse choices.
- Give an optional CLI count a typed default
Use type=int with an integer default for an optional count argument.
- Make two CLI modes mutually exclusive
Require exactly one of two command-line modes with an argparse mutually exclusive group.
- Parse repeated local labels with append
Collect repeated --label values in encounter order with argparse append.
- Use a subcommand to select a dry-run action
Select a dry-run operation with an argparse subcommand and dispatch it through a callable stored in the parsed namespace.
- Return a controlled parser error for an invalid mode
Catch an argparse choice failure and return a stable application-level message for an unsupported mode.
- Format a deterministic logging record
Use an explicit logging format with stable record fields to produce one predictable log line.
- Keep library logging quiet with a NullHandler
Attach NullHandler to a library logger so an unconfigured application does not receive output from that handler.
- Attach a named logger without configuring the root logger
Send records from one named logger to its own handler while leaving root logger handlers unchanged.
- Read an integer option from an INI string
Parse an INI string and retrieve a typed integer setting with ConfigParser.getint().
- Require an INI section before reading settings
Check an INI section with has_section() before reading its settings.
- Use INI interpolation for a derived local path
Use ConfigParser interpolation to derive a local path from another INI option.
- Preserve key case in a ConfigParser
Configure ConfigParser.optionxform to retain option-name case.
- Write an INI configuration to StringIO
Serialize an in-memory ConfigParser configuration to io.StringIO.
- Load a named standard-library module with importlib
Dynamically import the standard-library statistics module and call a named function.
- Reject a missing module spec before import
Use find_spec to recognize an unavailable module name and skip importing it.
- Inspect a module origin using find_spec
Find the sys module specification and inspect its built-in origin marker.
- Reload a fixture module after changing it
Create an isolated fixture module, alter its source, and reload the existing module object.
- Read a package text resource with files
Read UTF-8 text from a temporary package resource through importlib.resources.files.
- List package resource names without assuming filesystem paths
Use importlib.resources Traversable objects to enumerate package resources without requiring filesystem paths.
- Use as_file for a package resource path
Materialize a package resource as a temporary filesystem path only while an API needs one.
- Parse --verbose occurrences into a logging level
Count -v or --verbose flags with argparse and apply an explicit logging-level policy.
- Use argparse BooleanOptionalAction for a local switch
Define paired --cache and --no-cache command-line switches with BooleanOptionalAction.
- Read a fallback value from DEFAULT in ConfigParser
Let a section inherit an option from ConfigParser DEFAULT and distinguish it from the get() fallback argument.
- Validate a whole local identifier with fullmatch
Use re.Pattern.fullmatch() to accept only complete ASCII-style local identifiers.
- Extract numbered issue references without matching prefixes
Find bare #number issue references while excluding references embedded in ASCII word-like prefixes.
- Name groups in a build-label regular expression
Parse a structured build label into explicitly named fields with Python regular expressions.
- Replace only standalone TODO markers
Use word boundaries and re.Pattern.subn() to replace standalone TODO markers and count replacements.
- Split a colon-delimited local setting once
Separate a setting key from a colon-containing value with str.split(separator, 1).
- Use re.escape for a literal search token
Escape punctuation-bearing text before using it as a literal regular-expression search token.
- Report an invalid repeated separator with finditer
Find repeated colon and semicolon runs and report their exact source positions.
- Normalize line endings before a text comparison
Convert CRLF and CR line endings to LF before comparing text whose line-ending style is irrelevant.
- Strip a UTF-8 byte-order mark from a fixture
Read a controlled UTF-8 fixture with utf-8-sig so an initial BOM does not become text.
- Decode HTML character references safely
Convert named and numeric HTML character references to their Unicode characters with html.unescape.
- Collect text from selected HTML tags with HTMLParser
Use a small HTMLParser subclass to collect text only from chosen tags.
- Ignore HTML comments while collecting links
Collect real anchor targets with HTMLParser while comment contents remain non-links.
- Read HTML attributes without regex matching
Use HTMLParser attribute pairs instead of matching HTML source with regular expressions.
- Parse a small XML settings fixture
Parse a fixed XML settings document with ElementTree and assert the extracted values.
- Select XML children with a namespace map
Query namespaced XML children using ElementTree paths and a prefix-to-URI map.
- Require an XML attribute before converting it
Validate a required XML attribute before converting it to an integer with ElementTree.
- Serialize XML with stable attribute insertion order
Create attributes in an intentional order and serialize them predictably with ElementTree.
- Stream XML records with iterparse
Process completed XML records incrementally with ElementTree.iterparse.
- Distinguish missing XML text from an empty string
Classify absent elements, missing text, and explicitly assigned empty text with ElementTree.
- Use ElementTree.findall for direct child records
Select direct record children, excluding nested records, with ElementTree.findall.
- Find multiline log blocks with DOTALL
Extract bounded multiline log records with Python re.DOTALL.
- Use VERBOSE mode for a documented local pattern
Make a local identifier pattern easier to maintain with re.VERBOSE.
- Use a lookahead to keep overlapping tokens
Capture overlapping fixed-width tokens with a positive lookahead.
- Count substituted values with subn
Use re.subn to replace selected values and report the replacement count.
- Catch re.error for a supplied local pattern
Handle invalid locally supplied regular expressions during compilation.
- Read query parameters from a fixture URL
Parse a fixture URL and read decoded query values with urllib.parse.
- Preserve repeated query keys with parse_qsl
Keep repeated query keys and their order by parsing into pairs.
- Encode local query parameters with urlencode
Turn local parameter pairs into a correctly encoded query string.
- Replace a URL query without string concatenation
Replace only a URL query by splitting, updating, and reassembling components.
- Join a relative fixture link to a base URL
Resolve a relative fixture link against a base URL with urljoin.
- Reject a URL fixture with an unexpected scheme
Validate a fixture URL's parsed scheme against a small explicit allowlist.
- Separate a fragment from a local documentation URL
Use urldefrag to split a local documentation reference into a document URL and anchor.
- Normalize a percent-encoded query value
Decode one form-style query value and encode it again in a canonical percent-escaped form.
- Parse a Content-Type header with email.message
Parse a synthetic Content-Type header and read its normalized media type and parameters.
- Read a repeated response header from a local message
Use Message.get_all to retain every repeated Set-Cookie field in a synthetic header block.
- Parse a synthetic HTTP status line
Parse an isolated HTTP status line and validate its code with Python's HTTPStatus enum.
- Decode a chunked HTTP body fixture
Decode a controlled chunked-transfer byte fixture using explicit length and delimiter checks.
- Reject a malformed chunk length
Reject a non-hexadecimal chunk-size token before attempting to consume a chunk body.
- Split HTTP headers from a byte response fixture
Separate a byte response fixture into a start line, selected header values, and untouched body bytes.
- Decode a response body using a declared charset
Read a charset parameter from a Content-Type field and use it to decode response bytes.
- Choose a fallback charset for a text fixture
Use an explicit default encoding only when a byte fixture has no declared charset.
- Interpret a 204 response as having no body
Interpret a synthetic 204 response as an empty application-visible body while keeping trailing fixture bytes outside header parsing.
- Keep a relative redirect target unresolved
Parse a relative redirect target without inventing a base URL.
- Read a Location header from a local response
Extract a redirect Location value from fixed, local response-header bytes.
- Avoid treating plus signs as spaces in a URL path
Decode percent escapes in a URL path while preserving literal plus signs.
- Enable and prove a foreign-key constraint in memory
Enable SQLite foreign keys per connection and demonstrate rejection of a child row without a parent.
- Use a CHECK constraint for a bounded score
Keep integer scores within a declared 0–100 range and verify an out-of-range insert is rejected.
- Use a UNIQUE constraint to prevent duplicate local keys
Give a local configuration key a database-level uniqueness rule and test the duplicate path.
- Use a composite primary key for a mapping table
Model membership mappings whose identity is the pair of member and group identifiers.
- Handle a NOT NULL failure explicitly
Catch a missing required value as sqlite3.IntegrityError and preserve a clear application outcome.
- Use a transaction context manager for two inserts
Commit two related inserts with sqlite3.Connection used as a context manager.
- Roll back a transaction after a constraint failure
Handle a SQLite uniqueness violation and verify that the transaction's earlier insert was rolled back.
- Use SAVEPOINT to keep an earlier in-memory change
Undo a later SQLite insert while retaining an earlier insert in one in-memory transaction.
- Use parameter binding for a quoted search value
Search SQLite text containing an apostrophe by binding the value to a qmark placeholder.
- Count rows correctly with COUNT star
Use SQLite COUNT(*) when the requirement is to count every row, including rows with NULL values.
- Keep NULL separate from an empty string in a query
Query missing text and deliberately blank text with separate SQLite predicates.
- Use COALESCE for display fallbacks
Render a readable fallback for NULL without changing the stored value.
- Find unmatched rows with a LEFT JOIN
Use a LEFT JOIN and a NULL test to identify parent rows with no related rows.
- Avoid a join multiplication error by aggregating first
Aggregate independent one-to-many tables before joining their per-parent totals.
- Use EXISTS to test related-row presence
Return a per-row presence flag with a correlated EXISTS subquery.
- Use a correlated subquery for a per-group maximum
Return every score tied for the highest value within its team using SQLite from Python.
- Use HAVING after grouping local records
Filter grouped SQLite totals with HAVING after summing local time-entry rows.
- Order deterministic query output with a tie breaker
Add a unique secondary sort key so tied SQLite priorities have a defined output order.
- Use a window row number for ranked fixture rows
Assign sequential per-division fixture positions with SQLite ROW_NUMBER().
- Use a CTE to name a filtered local set
Name filtered in-memory SQLite event rows with a common table expression before aggregation.
- Use INSERT OR IGNORE and inspect rowcount
Detect whether a unique-key insert added a row without raising on a duplicate.
- Use an UPSERT that updates one column
Update only a chosen column when an insert conflicts with an existing primary key.
- Check changes after a deliberate update
Confirm the count reported by SQLite after an update chosen to affect one row.
- Set row_factory to sqlite3.Row for named columns
Fetch SQLite rows that support both named and positional column access.
- Use executemany inside one transaction
Insert a small parameter sequence with executemany under one transaction.
- Store and retrieve a BLOB fixture
Store deterministic binary fixture bytes in an in-memory SQLite BLOB column and retrieve them unchanged.
- Register an adapter-free named parameter query
Use SQLite named placeholders with native Python values, without registering a custom adapter.
- Use EXPLAIN QUERY PLAN for an indexed lookup
Check that an in-memory SQLite lookup plan mentions a deliberately created index.
- Create a partial index for active rows
Create an SQLite partial index that contains entries only for rows whose active flag is 1.
- Use a deferred foreign key within one transaction
Insert a child before its parent, resolve the relationship, and commit one SQLite transaction.
- Why does a unittest fixture retain data between tests?
Reproduce class-level list leakage and recreate the mutable object in setUp.
- Run unittest cleanup even when setUp raises
Use addCleanup to release acquired state on the fixture setup-failure path.
- Why is a contextmanager generator required to yield exactly once?
Compare zero-yield, single-yield, and two-yield generator context-manager lifecycles.
- Collect all table-driven failures with unittest subTest
Contrast a stopping loop with subTest failure events for boundary inputs.
- Compare unordered lists that contain dictionaries in unittest
Use assertCountEqual for order-insensitive comparisons of mappings while retaining duplicate counts.
- Stop assertAlmostEqual from accepting the wrong numeric tolerance
Contrast decimal-place comparison with an explicit absolute error boundary.
- Treat assertRaisesRegex patterns as regular expressions
Show why literal punctuation must be escaped and when strict anchors are needed.
- Test a warning without hiding unrelated warning categories
Capture the expected warning while retaining evidence for another category.
- Keep long unittest diffs available when debugging a mismatch
Compare bounded and unlimited unittest diagnostic output without snapshotting it.
- Restore a patched mapping after an exception with patch.dict
Prove that patch.dict restores an in-memory mapping after exceptional exit.
- Patch the lookup namespace when a dependency was imported directly
A synthetic reproduction of a provider patch that installs successfully but misses a consumer's already-bound dependency.
- Catch an outdated call signature with create_autospec
Contrast a loose Mock with create_autospec to expose a misspelled keyword before an integration test.
- Use spec_set to reject accidental mock attributes
Show the difference between spec's restricted reads and spec_set's restricted reads and writes.
- Why does Mock side_effect stop with StopIteration?
Demonstrate iterable side_effect exhaustion and contrast it with an intentional callable fallback.
- Reset mock call history without silently changing behavior
Separate a Mock's recorded interactions from its configured return and side-effect behavior during reset_mock().
- Distinguish a mocked async call from an awaited call
Use AsyncMock call and await counters to prove that a coroutine was consumed.
- Verify a mock call sequence without forbidding extra calls accidentally
Contrast sequence inclusion with equality against a complete mock interaction history.
- Test which exception a suppress block actually handles
Demonstrate that suppress(KeyError) handles missing keys but lets ValueError propagate.
- Use ExitStack to unwind partially acquired resources
Verify LIFO cleanup after a synthetic third-resource acquisition failure.
- Transfer cleanup ownership with ExitStack.pop_all
Transfer registered callbacks to a new stack and verify deferred LIFO cleanup.
- Avoid suppressing an exception accidentally inside a contextmanager
Compare a logging-only generator context manager with one that logs and re-raises the same sentinel exception.
- Keep a caller-owned stream open with nullcontext
Use nullcontext for a supplied StringIO while a helper-created StringIO remains owned and closes on exit.
- Prevent redirect_stdout from swallowing a diagnostic after an exception
Raise inside redirect_stdout, catch outside, and verify stdout identity restoration plus captured output.
- Sort a list in a test without mutating the expected fixture
Expose an aliased, mutated oracle and contrast it with snapshots that detect in-place sorting.
- Detect when shallow copies fail to isolate nested test data
Show the nested-list alias left by dict.copy and contrast it with deepcopy isolation.
- Avoid shared iterator exhaustion across repeated tests
Separate reusable source data from a single-pass iterator by testing the two observed consumption sequences.
- Use assertLogs without depending on timestamps or handler formatting
Use assertLogs LogRecord fields to test a logging event without snapshotting timestamp-bearing rendered lines.
- Test generator failures at iteration time instead of construction
Place next() inside assertRaises to test when a generator body actually raises.
- Keep custom equality assertions from hiding object identity bugs
Contrast value equality with identity assertions when an API must return a particular object.
- Report unexpected success in an expectedFailure unittest
Run controlled expected-failure cases and inspect why a stale marker leaves the result unsuccessful.
- Reject non-alphabet characters during strict Base64 decoding
Compare permissive and strict Base64 decoding when punctuation appears in encoded input.
- Capture printed diagnostics with redirect_stderr
Capture a validator's stderr diagnostic while confirming it produced no stdout.
- Diagnose an odd-length hexadecimal field before unhexlify
Separate an odd hexadecimal digit count from non-hexadecimal input before conversion.
- Decode a UTF-8 character split across byte chunks incrementally
Use an incremental UTF-8 decoder to retain incomplete trailing bytes between chunks.
- Use closing for an iterator with a close method
Ensure an iterator's close method runs when an early loop exit leaves its block.
- Separate bisect insertion position from exact membership
Use bisect_left with a bounds-and-equality check to distinguish insertion positions from exact matches.
- Use a heap counter to avoid comparing dictionary payloads on ties
Add a monotonic counter to heap entries so tied priorities do not compare opaque dictionary payloads.
- Use contextmanager to time a pure in-memory block
Put timing cleanup in a contextmanager finally block so it runs when the block raises.
- Explain why ContextDecorator can hide shared state
Use a decorator factory to give each ContextDecorator-managed call independent mutable state.
- Return a sentinel instead of catching every Exception
Use an identity-checked sentinel to distinguish absent dictionary keys from values such as None.
- Preserve the original exception with raise from
Wrap an invalid configuration value while retaining its ValueError as the explicit cause.
- Format a short exception-only diagnostic
Use traceback.format_exception_only to render a controlled ValueError message without traceback frames.
- Extract an exception type without exposing traceback paths
Use a type-only status field when a caught KeyError's message and formatted traceback are not reportable.
- Use ExceptionGroup except star for independent validation failures
Collect independent validation errors and selectively handle their ValueError and TypeError members.
- Distinguish KeyError from a missing optional value
Preserve a present optional null while rejecting an absent required nested key at a configuration boundary.
- Reject a bool where an integer option is required
Use type(value) is int when an option must accept only exact integers, not bool or float lookalikes.
- Turn a parser failure into a structured result object
Convert an integer parsing ValueError into an explicit success-or-error result rather than returning ambiguous None.
- Avoid mutable error details in a reusable exception
Copy caller-provided validation details when constructing an exception so later dict mutation cannot rewrite the reported error.
- Use a custom exception for an invalid state transition
Raise an InvalidTransition exception with from_state and to_state attributes when a workflow transition is not allowed.
- Attach a stable error code to a validation error
Put stable machine-readable codes on validation exceptions so consumers branch on codes instead of human messages.
- Keep finally cleanup from masking the main error
Preserve a ValueError when a cleanup action also fails in a finally clause.
- Use try else to separate successful parsing from recovery
Keep JSON parsing recovery separate from work that happens after a successful parse.
- Recognize an unhandled BaseException boundary
Allow KeyboardInterrupt to pass through an ordinary application-error boundary.
- Report the index of a rejected sequence item
Use enumerate to report both the location and value of the first rejected item.
- Validate all items and raise an ExceptionGroup
Collect negative-value and non-integer validation failures in one ExceptionGroup.
- Use a context manager to restore a module-level setting
Restore a temporary module-level setting with a context manager, even when the body raises an exception.
- Handle StopIteration at an iterator consumer boundary
Consume an iterator safely with a sentinel so exhaustion is distinct from a stored None value.
- Avoid catching GeneratorExit in library code
Let GeneratorExit propagate through generator cleanup instead of swallowing BaseException.
- Make a retry decision from explicit exception classes
Choose retries by exception type so a similar error message cannot retry a permanent failure.
- Disable SequenceMatcher autojunk for a repeated short alphabet
Compare SequenceMatcher matching blocks with autojunk enabled and disabled on repetitive A/B data.
- Reject duplicate JSON object names with object_pairs_hook
Reject repeated JSON object names before dictionary conversion silently discards an earlier value.
- Decode a JSON number as Decimal for an amount field
Use parse_float=Decimal to preserve a decimal JSON amount through arithmetic.
- Reject NaN in a local JSON fixture
Use parse_constant to reject the non-standard NaN token accepted by Python's default JSON decoder.
- Detect JSON key collisions after Unicode normalization
Normalize JSON object names to NFC inside object_pairs_hook and reject policy-level collisions with both original spellings.
- Use a JSON encoder default only for one tagged value type
Encode UUID values as tagged objects while continuing to reject unsupported sets.
- Differentiate a JSON null from an omitted mapping key
Preserve omission and explicit JSON null as separate update instructions after decoding.
- Limit a JSON fixture before decoding from StringIO
Enforce a character limit with read(limit + 1) before decoding a StringIO JSON fixture.
- Report a JSONDecodeError line and column without printing the source
Build a location-only parse-error report from JSONDecodeError.lineno and colno.
- Validate a JSON list contains only objects
Validate each decoded list item is a dict before code assumes object methods such as get().
- Keep an unknown JSON field for forward-compatible reporting
Validate known fields while retaining unrecognized fields for a forward-compatible report.
- Build a JSON pointer-like path while validating nested fields
Validate nested decoded JSON while reporting a precise $.users[0].name location.
- Treat JSON iterencode chunks as fragments of one document
Join JSONEncoder.iterencode fragments before decoding the complete JSON document.
- Require a JSON object instead of accepting a list
Require an exact dict after JSON decoding rather than relying on iterability.
- Coerce a JSON boolean only when it is actually bool
Accept a decoded JSON boolean only when its exact Python type is bool.
- Validate an integer JSON field without accepting float
Validate a root JSON object count as an exact Python int, rejecting arrays, floats, booleans, and duplicate root count members without rejecting nested objects.
- Reject a JSON array with a duplicate logical identifier
Decode an array, then enforce identifier uniqueness with an index-aware validation error.
- Convert a JSON timestamp field only after a type check
Decode JSON first, demonstrate the type errors from unchecked parsing, then parse only the documented string timestamp form.
- Use object_hook to construct a tiny value object
Limit a JSON object_hook to an exact tagged shape before creating a Point value object.
- Keep JSON decoding separate from domain validation
Treat valid JSON syntax as a separate concern from a non-negative count business rule.
- Project a cyclic dataclass graph without calling asdict recursively
Replace recursive asdict on a cyclic Node with a bounded projection that emits a cycle marker.
- Build a synthetic JSON Lines fixture in memory
Build an in-memory JSON Lines fixture by writing one JSON object and one newline per record.
- Report the first invalid JSON Lines record number
Decode JSON Lines one record at a time to report the first malformed record.
- Keep a JSON schema-like required-field check small
Decode a small JSON object and report its missing required fields with a sorted set difference.
- Compare parsed JSON structures instead of raw whitespace
Parse equivalent JSON texts before comparison to ignore formatting-only differences.
- Use ensure_ascii deliberately for a text contract
Choose whether JSON fixtures escape non-ASCII characters with ensure_ascii.
- Reject non-string JSON mapping keys before encoding
Reject Python mapping keys that JSON would coerce before encoding.
- Avoid treating an empty JSON object as a missing value
Use an explicit None check so an empty decoded JSON object remains present.
- Test a JSON encoder with a nested Decimal rejection
Test that a JSON encoder rejects an unsupported Decimal even when it is nested.
- Preserve list order when it has domain meaning
Keep workflow steps in their supplied JSON-array order while canonicalizing only object-key presentation where the contract permits it.
- Inspect how dedent treats mixed tab and space prefixes
Make mixed indentation visible before applying an explicit tabs-to-spaces fixture policy.
- Fetch every row from SQLite UPDATE RETURNING before reading rowcount
Consume an UPDATE RETURNING cursor before trusting sqlite3.Cursor.rowcount, while keeping returned IDs separate from the change count.
- Replace SQLite NOT IN when the subquery can return NULL
Show why a NULL in a NOT IN subquery can filter every candidate, and use correlated NOT EXISTS for absence of a match.
- Find the second newest row with ORDER BY and OFFSET
Use descending ORDER BY with LIMIT 1 OFFSET 1 to select the second newest distinct-date row rather than the newest value from MAX().
- Use a CASE expression to label a bounded score
Contrast a boolean range test with CASE labels that identify whether a score is low, acceptable, or high.
- Count distinct non-null values in a fixture table
Compare COUNT(*), COUNT(column), and COUNT(DISTINCT column) on duplicates and NULL to count distinct non-null values.
- Explain why SUM of no rows is NULL
Reproduce SQLite's empty-set aggregate behavior and contrast SUM with total.
- Use FILTER with an aggregate for a conditional count
Count each store’s paid SQLite orders with an aggregate FILTER instead of an uncorrelated global scalar subquery.
- Find rows whose value is outside a local range
Contrast inclusive BETWEEN with the explicit SQLite predicate for range violations.
- Use a recursive CTE to generate a short integer series
Generate a bounded inclusive SQLite integer series with a terminating recursive CTE.
- Compare two in-memory tables with EXCEPT
Express the distinct left-only identifier set in SQLite with EXCEPT.
- Find values present in either table with UNION
Combine values from two SQLite tables and remove the shared value with UNION.
- Keep duplicate rows visible with UNION ALL
Use UNION ALL in SQLite when two identical result rows must remain visible.
- Use CROSS JOIN deliberately for a small option matrix
Generate all size-and-color pairs with SQLite CROSS JOIN and verify the four-row matrix.
- Set an explicit whole-partition frame for SQLite last_value
Use an explicit ROWS frame so SQLite last_value reports the final value for every row in a partition.
- Detect ties for a maximum value with RANK
Use RANK() = 1 to return all SQLite rows tied for the maximum score.
- Use LAG to calculate a change between ordered rows
A reproducible in-memory SQLite example showing why LAG needs window ordering.
- Use LEAD to inspect the next scheduled value
An in-memory SQLite experiment comparing a self-join with LEAD for the next schedule time.
- Compute a running average with a window frame
A SQLite window-frame experiment that makes a two-row running average explicit.
- Use a window partition for per-category totals
An in-memory SQLite comparison of a global window sum and per-category totals.
- Match the exact expression used by a SQLite expression index
A reproducible EXPLAIN QUERY PLAN comparison for x+y and y+x against an expression index.
- Use a covering index for a narrow lookup
Verify that a SQLite lookup can return its selected column from an index alone.
- Check an index definition with PRAGMA index_info
Verify both the ordered columns and partial-index status of a SQLite index in an in-memory test.
- Inspect foreign-key violations in an in-memory database
Use PRAGMA foreign_key_check to reveal an orphaned child row in a synthetic SQLite fixture.
- Use sqlite3.Row with duplicate column aliases carefully
Avoid ambiguous sqlite3.Row key access by assigning distinct SQL aliases.
- Bind an IN list by creating placeholders from trusted length
Generate one SQLite placeholder per IN-list value and bind the values separately.
- Avoid string-formatting a SQL ORDER BY direction
Reject untrusted ORDER BY directions and map approved values to fixed SQL tokens.
- Use a read-only SELECT transaction for a consistent fixture snapshot
Keep related reads on one SQLite snapshot with an explicit transaction.
- Set a busy timeout only as a bounded local policy
Use sqlite3 connection timeouts as a short, explicit contention policy rather than unbounded retries.
- Use connection total_changes for a controlled fixture update
Measure one known SQLite update using a Connection.total_changes delta.
- Explain sqlite3 cursor rowcount after SELECT
Use fetched result length, not Cursor.rowcount, to count SQLite SELECT results.
- Parse a fixed-point amount while rejecting surrounding currency text
Keep a permitted currency column separate from a strict fixed-point amount token, then validate the whole amount field before Decimal conversion.
- Use Decimal compare_total for a deterministic sort of special values
Adapt Decimal.compare_total with functools.cmp_to_key to sort signed zero and NaN representations without relying on ordinary numeric equality.
- Preserve or collapse Decimal signed zero by an explicit display policy
Make Decimal signed zero visible and choose a declared rendering policy instead of letting equality erase the distinction.
- Use localcontext to isolate a temporary Decimal precision change
Use decimal.localcontext to calculate at a temporary precision without leaking that setting to later Decimal work.
- Trap Decimal division by zero in a validation helper
Turn a Decimal DivisionByZero signal into a structured validation result instead of allowing Infinity through.
- Detect an inexact Decimal operation with context flags
Detect precision loss from Decimal division by clearing and checking the Inexact context flag.
- Convert an integer minor-unit amount to Decimal safely
Convert integer minor units using Decimal.scaleb with a local precision sufficient for the integer coefficient.
- Measure Fraction limit_denominator approximation error exactly
Approximate a Fraction under a denominator cap and report its exact residual.
- Compute a percentage from Decimal values without float conversion
Keep Decimal records unchanged, expose the float-conversion boundary, and calculate an exact 37.5 percent with a local Decimal context.
- Reject a negative quantity before multiplying an amount
Validate a negative quantity before calculating a Decimal line total.
- Assign values to half-open intervals with bisect boundaries
Use bisect_left or bisect_right as an explicit, tested interval-boundary policy.
- Group records by two selected mapping fields
Group records by a tuple made from exactly the fields that define the group.
- Choose explicit byte order to avoid native struct padding
Specify a standard struct prefix for portable binary wire records.
- Pivot a small in-memory list of records into totals
Accumulate Decimal amounts by category without mutating the source records.
- Unpivot a fixed mapping into name-value rows
Emit name-value rows in an explicit schema order rather than mapping insertion order.
- Join two mapping lists on a unique synthetic key
Validate synthetic-key uniqueness before joining mapping lists so duplicate records cannot multiply result rows unnoticed.
- Report keys present only on one side of two mappings
Compare mapping key sets, rather than values, to report keys missing from either side.
- Apply a whitelist of allowed mapping fields
Build a new mapping from explicitly allowed fields so unwanted fields are not copied.
- Rename selected mapping fields without mutating the input
Build a renamed mapping with a comprehension instead of using pop on caller-owned data.
- Avoid eager default construction when dict.get finds an existing value
Use an explicit key-membership branch when a fallback factory must run only for a missing key, even when a stored value is None.
- Observe independent positions after splitting an iterator with tee
A five-line transcript shows that tee branches advance independently.
- Sort casefold-colliding Unicode labels with a deterministic tie breaker
Make Unicode casefold collisions visible, then choose either display text or a stable record ID as the explicit tie-breaking policy.
- Use min and max together for a range summary
A guarded one-pass loop summarizes a one-shot iterator and returns None for empty input.
- Calculate a bounded moving average from a short list
A deque retains only full three-value windows and skips partial averages.
- Reject trailing text in a datetime field instead of slicing it away
Parse the complete field so unexpected trailing text becomes a visible validation error.
- Find the first record that violates monotonic order
Detect the first descending timestamp in source order without sorting away the evidence.
- Build a histogram from integer buckets
Count fixed-width integer buckets with floor division while preserving the input records.
- Normalize percentages so the displayed total is exactly 100
Use Decimal and largest-remainder allocation to make displayed percentages total 100.00.
- Select the smallest records with an explicit stable heap tie key
Use heapq.nsmallest with original indexes to state the equal-score tie contract.
- Fail on missing string.Template placeholders before shipping a report
Use strict Template substitution to reject incomplete report data while preserving literal dollars.