SkilVaultSign inStart free

Catalogue / python-code-and-design

python-code-and-design

Older skill: source not recordedSignedWrites, reviews, debugs and refactors Python with concrete language, design, concurrency and testing recipes. Use when asked to review Python, simplify a function, fix asyncio, choose a dataclass, add tests, or package a Python project. Not for operating production services or publishing a package w…
---
name: python-code-and-design
description: >-
  Writes, reviews, debugs and refactors Python with concrete language, design, concurrency and testing recipes. Use when asked to review Python, simplify a function, fix asyncio, choose a dataclass, add tests, or package a Python project. Not for operating production services or publishing a package without a separate release plan.
---

Python code and design

Start from the behavior that must remain true, the supported Python version and a small example. Prefer a plain function for stateless work, a dataclass for records, a class for state plus behavior.

Working contract

Discussion and suggested code stay in the conversation unless saving or execution is requested. For repository edits, confirm affected files and intended behavior first; a confirmed scope covers ordinary corrections within it.

| Action | Confirm before acting | |---|---| | Format/refactor files | Paths, behavior constraints, formatter scope | | Install/sync packages/Python | Environment, pinned versions, lockfiles | | Run tests or subprocesses | Fixtures, commands, writes, cleanup | | Write database records | Database, transaction, rows touched | | Build/publish/install hooks | Destination, index, version, hook scope |

Ten decisions to carry through a change

  1. Name intermediate values when an expression needs decoding.
  2. Follow the project's formatter and naming rules.
  3. Choose containers from access and mutation requirements.
  4. Compose collaborators; inherit only for substitutable types.
  5. Keep public functions focused, documented and typed.
  6. Extract shared rules when repetition is real, not speculative.
  7. Propagate or handle specific failures with useful context.
  8. Verify component integration and difficult boundaries.
  9. Separate the policy that changes from the workflow that stays stable.
  10. Work in small tested revisions; backtrack when the design worsens.

Containers by operation

| Need | Choice and limit | |---|---| | Mutable ordered items | list: O(1) index/append; O(n) front removal, membership | | Fixed record | tuple/NamedTuple; hashable only if every member is | | Named fields | dataclass; frozen=True blocks assignment, not mutation of a list field | | Key lookup | dict: insertion-ordered, average O(1) | | Membership/dedup | set: O(1) average; frozenset for set keys | | FIFO/both ends | deque: O(1) at either end; bounded drops the oldest opposite item | | Priority order | heapq: O(log n); counter when priorities tie uncomparable | | Frequencies | Counter; most_common ranks counts | | Grouping | defaultdict(list); factory runs for missing indexed keys | | Exact decimals | Decimal from strings; rounding context still applies |

| Operation | Syntax and behavior | |---|---| | Slice | items[:4]; bounds clip; slice assignment can resize | | Copy | .copy() shares nested members; copy.deepcopy recurses | | Singleton tuple | ('owl',) — ('owl') is a string | | Dict fallback | .get(k, fb) evaluates fb eagerly; __missing__ covers d[k], not get | | Merge | a \| b / \|=: right wins; {**a, **b} for older versions | | Reverse mapping | {v: k for k, v in pairs} drops dup values | | Set algebra | a\|b, a&b, a-b, a^b, a<=b | | Sort | sorted(x) returns a list; .sort() mutates, returns None | | Multi-key | sorted(rows, key=lambda r: (r['g'], r['n'])); stable passes mix direction | | Binary search | bisect_left finds insertion point, not equality; insert stays O(n) | | Binary buffers | bytes immutable, bytearray mutable, memoryview shares |

from bisect import bisect_left
from itertools import groupby, product, permutations, combinations, count
from collections import deque
import heapq
i = bisect_left([3, 7, 12], 7); found = i < 3 and [3, 7, 12][i] == 7
runs = [(k, list(g)) for k, g in groupby('aabbc')]  # adjacent keys; sort for global grouping
pairs = list(product('ab', [1, 2])); picks = list(combinations('abc', 2))
heap, tie = [], count()               # tie-breaker for uncomparable priorities
heapq.heappush(heap, (2, next(tie), 'review'))
queue = deque([1, 2], maxlen=4)       # maxlen drops the oldest on overflow

Syntax that communicates intent

| Rule | Instead of | Write | |---|---|---| | Name fields | city = record[2] | name, age, city = record | | Capture remainder | scores[1:-1] | a, *mid, b = scores | | Swap | temp variable | a, b = b, a | | Mutable default | def f(x, items=[]) | items=None, allocate per call | | Empty test | len(items)==0 | not items | | Negated identity | not v is None | v is not None | | Numbered loop | range(len(x)) | enumerate(x, start=1) | | Aligned pairs | zip(a, b) truncates | zip(a, b, strict=True) | | Delete while looping | items.remove(x) in its loop | Comprehension | | Join | repeated text += piece | ''.join(pieces) | | Branching | nested conditional expressions | Helper or if/elif | | Reuse a match | search twice | if m := pat.search(t): ... |

Falsy: False, None, zero numbers, empty text/bytes/collections, false __bool__, zero __len__. Separate missing from valid zero with is None.

items = [] if items is None else items  # mutable-default fix: allocate per call
for n, (name, score) in enumerate(zip(['Maya', 'Noor'], [8, 9], strict=True), 1):
    print(f'{n}: {name!r} scored {score:.1f}')
squares = [x*x for x in nums]           # list comprehension
lookup = {str(x): x*x for x in nums}    # dict comprehension
lengths = {len(w) for w in ['fox', 'owl']}  # set comprehension
lazy = (round(x**.5, 2) for x in nums)  # generator: consumed once

| Style element | Convention | |---|---| | Indentation | Four spaces; follow repository formatter config | | Line length | PEP 8: 79; Black 88 unless configured | | Blank lines | Two between top-level defs, one between methods | | Names | load_record, ReportClient, MAX_RETRIES | | Attributes | _cache marks internal; __name mangles vs subclass collisions, not security | | Receivers | self for instances, cls for classmethods | | Spacing | x = 3, {'k': 3}, timeout=3, x: int | | Imports | stdlib, third-party, local; absolute; no wildcards | | Output | str for readers, repr for diagnostics; redact sensitive fields |

Keep comprehensions to about two for/if clauses; extract harder work. := in a comprehension binds in the enclosing scope; its loop variables do not. Loop else runs only without break.

Pattern matching and regular expressions

from dataclasses import dataclass
@dataclass
class Click:
    x: int; y: int
def describe(event):
    match event:
        case Click(x=x, y=y) if x >= 80: return ('right', x, y)  # guard
        case Click(x=x, y=y): return ('left', x, y)
        case {'action': 'quit'}: return ('quit',)   # mapping pattern
        case ['go', direction]: return ('move', direction)       # sequence pattern
        case str() as s: return ('text', s)   # class check + capture
        case _: return ('unknown',)

Match destructures; bare names capture, dotted constants compare. The example returns intentions, not actions.

| Regex operation | Example | |---|---| | Anchor / search | re.match(r'ID-', t) / re.search(r'ID-\d+', t) | | All matches | re.findall(r'\b\w+\b', t) | | Replace / split | re.sub(r'\s+', ' ', t) / re.split(r'[,;]', t) | | Reuse | re.compile(r'(?P<year>\d{4})/(?P<month>\d{2})') |

| Token | Meaning | |---|---| | \d \w \s | Digit, word char, whitespace; Unicode-aware unless ASCII set | | . | Any character except newline by default | | * + ? {n,m} | Zero-or-more, one-or-more, optional, bounded repeat | | [abc] | One character from the set | | ^ $ | Anchors; $ also matches before a final newline |

import re
STAMP = re.compile(r'(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})')
if m := STAMP.search('Filed on 2026/09/14'):
    year = int(m.group('year'))       # named groups beat indexes

Function contracts and lazy work

def ratio(numerator, denominator, /, *, fallback=None):
    """Positional-only inputs, keyword-only option; raise, never ambiguous None."""
    if denominator == 0:
        if fallback is not None:
            return fallback
        raise ZeroDivisionError('ratio denominator is zero')
    return numerator / denominator

| Contract feature | Guidance | |---|---| | / | Positional-only names never become caller keyword dependencies | | * | Keyword-only options make optional behavior explicit | | *args | Extra positional values; inserting an earlier parameter can silently break callers | | **kwargs | Named options; validate accepted keys at the boundary | | References | Mutable arguments can change; document mutation or copy defensively | | Dynamic defaults | Compute time or allocate collections inside the function | | Returns | Named result dataclass for several fields; Optional only when absence is contractual | | Failures | Raise for invalid input; never overload valid zero/empty/None | | Docstrings | Purpose, arguments, result, exceptions; annotations carry types |

from functools import wraps, partial
import math
def count_calls(function):             # decorator done right: wraps + nonlocal
    calls = 0
    @wraps(function)
    def wrapped(*args, **kwargs):
        nonlocal calls
        calls += 1
        wrapped.calls = calls
        return function(*args, **kwargs)
    wrapped.calls = 0
    return wrapped
log_two = partial(math.log, base=2)    # pin keyword arguments
assert log_two(16) == 4

LEGB: Local, Enclosing, Global, Built-in. nonlocal rebinds closure state, global module state. Prefer explicit state objects when lifetime or concurrency complicates closures.

| Decorator | Purpose | |---|---| | property | Managed attribute; setter can validate | | staticmethod / classmethod | No receiver / receives the class, good for alternate constructors | | lru_cache / cache | Memoization; mind bounds, invalidation, hashable arguments | | singledispatch | Dispatch on the first argument's type | | dataclass | Generates record methods; defaults and equality configurable |

yield turns a function into a lazy producer; yield from delegates to a sub-iterator. send injects a value into a suspended generator, throw an exception — prefer input iterators otherwise. A generator owning a resource must be closed explicitly on early termination; keep with open(...) in the caller's hands.

from functools import cache
@cache
def fibonacci(index):                  # memoized recursion
    return index if index < 2 else fibonacci(index-1) + fibonacci(index-2)
def arrange(remaining, chosen=()):     # backtracking without mutation
    if not remaining:
        yield chosen; return
    for i, value in enumerate(remaining):
        yield from arrange(remaining[:i] + remaining[i+1:], chosen + (value,))

With mutable backtracking state, undo each choice in finally even when the branch raises. Memoization removes repeated subproblems, not recursion-depth limits or unbounded cache growth. Lambdas fit one simple expression; partial for binding.

Objects, interfaces and contracts

| Decision | Practical rule | |---|---| | Responsibility | Keep each class cohesive; separate driving a vehicle from scheduling its maintenance | | Coupling | Depend on public operations, not chains of another object's internals | | Variation | Inject a pricing/filtering policy instead of scattering conditionals | | Extension | Compose, subclass, or configure only where real variation exists | | Predictability | Attribute reads cheap; expensive or I/O work is a named method | | Substitution | Subclasses may not strengthen preconditions or weaken postconditions | | Process | Build a working version, isolate variation, delegate, test, revisit poor choices |

from dataclasses import dataclass, field

Preview shortened. The full SKILL.md is in the pack.