Python Core Patterns
Modern Python development patterns targeting 3.13+ for minimal, efficient, reusable, and performant code.
Quick Start
New code: Use @dataclass(slots=True) for data classes, PEP 695 generics (def first[T](...)), Protocol for structural typing, TaskGroup for async concurrency.
Performance: Profile first with py-spy or scalene. Use generators for single-pass iteration, set for membership tests, connection pooling for I/O.
Minimalism Patterns
- Use walrus operator (
:=) in while-loops and comprehension filters to eliminate duplicate calls — avoid in deeply nested expressions - Prefer
match/caseover if-elif chains for structural/type dispatch; powerful with dataclass destructuring - Use
@dataclass(frozen=True)for value objects,@dataclass(slots=True)for memory savings (~200 bytes/instance) - Use
NamedTuplefor lightweight immutable records;dataclasswhen you need defaults, mutability, or methods - Always use
field(default_factory=list)for mutable defaults — neverdef f(items=[]) - Prefer
dict.get(key, default)overif key in dictfor simple lookups - Use
contextlib.suppress(Exception)instead of emptytry/except/pass
Efficiency Patterns
- Generator expressions for single-pass iteration; list comprehensions for building lists (20-30% faster than loops)
__slots__or@dataclass(slots=True)reduces per-instance memory by 200+ bytessetfor membership testing (O(1) vs O(n) for lists),frozensetfor hashable setsstr.join()over+=for string building; f-strings over.format()(fastest string formatting)itertoolsfor composable lazy iteration:chain,islice,groupby,batched(3.12+)memoryviewfor zero-copy binary slicing on large buffers@functools.lru_cache/@functools.cache(3.9+) for memoization of pure functionscollections.dequefor O(1) append/pop from both ends;defaultdictto avoid key existence checks- Batch database operations — use
executemany()or bulk inserts, never N+1 loops
Code Reuse
- Protocol over ABC when you want structural typing without inheritance — duck typing with type safety
- ABC when you need shared implementation or runtime
isinstance()enforcement - Composition over inheritance;
functools.partialfor specialization without subclassing functools.cached_propertyfor one-time expensive computed attributes (thread-safe in 3.12+)- Small, single-responsibility Protocols composed together beat large interfaces
- Use
typing.overloadfor functions with type-dependent return signatures - Extract shared logic into standalone functions, not base classes — flat is better than nested
Modern Python (3.13+)
- PEP 695 generics (3.12+):
def first[T](lst: list[T]) -> T:replacesTypeVarboilerplate (60% reduction) typestatement (3.12+):type Vector = list[float]replacesTypeAliasTypeIs(3.13) preferred overTypeGuard— narrows both branches of conditionalTaskGroup(3.11+) replacesasyncio.gather()— structured concurrency with auto-cancellation on failureexcept*(3.11+) for handlingExceptionGroupfrom concurrent failures- Never swallow
CancelledError; calltask.result()outside theasync withblock tomllibin stdlib (3.11+) for TOML parsing — no external dependency neededReadOnlyTypedDict items (3.13) for immutable typed dict fields
Performance
- Profile first:
cProfilefor call counts,py-spy/scalenefor line-level profiling,tracemallocfor memory leaks TaskGroupfor structured async I/O concurrency;ProcessPoolExecutorfor CPU-bound offloading- Connection pooling mandatory for databases and HTTP — never open/close per request
- Eager-load related data to prevent N+1 queries; use
selectinload()in SQLAlchemy uvloopfor 2-4x async event loop throughput (drop-in replacement for asyncio loop)- Pre-allocate collections when size is known:
list(range(n)),bytearray(n) - Avoid
globallookups in tight loops — assign to local variable first - Free-threaded mode (3.13t) shows ~80% improvement for multi-threaded CPU tasks — experimental, not for production
Type Safety
mypy --strictfor new projects; gradual adoption with--disallow-untyped-defsfor existingProtocolfor structural subtyping — don't force users to inherit from your base classParamSpec+Concatenatefor typing decorators that modify function signaturesSelftype (3.11+) for fluent method chaining returnsTypedDictfor typed dictionaries with known keys;Unpackfor kwargs typing- Run mypy in CI with zero tolerance for type errors on new code
Anti-Patterns
- ❌ Mutable default arguments:
def f(items=[])— shared across calls - ❌ Bare
except:— catchesKeyboardInterrupt,SystemExit; useexcept Exception: - ❌
eval()/exec()on untrusted input — injection vulnerability - ❌ Inconsistent return types: sometimes
None, sometimes value — useOptional[T]explicitly - ❌
isinstance()chains instead of polymorphism ormatch/case - ❌ Ignoring
withstatements for file/connection/lock resources - ❌ Cargo-cult patterns:
@propertygetters that just return an attribute - ❌ LBYL (Look Before You Leap) — prefer EAFP (Easier to Ask Forgiveness)