Python Coding Guidelines
Requirements
- Python ≥ 3.12; pytest ≥ 8.
Essentials
- Data models - Use dataclasses and type hints, see references/dataclasses-type-hints.md, references/type-checking.md
- Iteration - Prefer generators/comprehensions for data processing, see references/generators-comprehensions.md
- Performance - Cache pure functions with
@cache, see references/caching-functions.md - Resource management - Use context managers for cleanup, see references/resource-management.md
- Modern syntax - Use pathlib, f-strings, specific exceptions, see references/pathlib-file-ops.md, references/string-formatting.md, references/exception-handling.md
- Paradigm - Functional style → fp-guide; class/OO design → oop-guide
Gotchas
- Mutable default arguments (
def f(x=[]):) share state across calls: useNoneand assign inside - The GIL serializes pure-Python execution: threads only help on I/O; CPU-bound work needs
multiprocessingor compiled extensions ischecks identity, not equality: small-int caching meansa is bworks for1but fails for300__init__.pyis no longer required for packages (PEP 420), but mixing namespace and regular packages causes silent import-shadowing bugs
Progressive disclosure
- Read references/dataclasses-type-hints.md - Load when defining structured data models or adding type annotations
- Read references/type-checking.md - Load when using Protocols, type aliases, or complex Union types
- Read references/resource-management.md - Load when working with files, connections, or resources needing cleanup
- Read references/caching-functions.md - Load when optimizing expensive computations or repeated function calls
- Read references/generators-comprehensions.md - Load when processing large datasets or streaming data
- Read references/string-formatting.md - Load when formatting output, building messages, or templating
- Read references/pathlib-file-ops.md - Load when reading/writing files or traversing directories
- Read references/exception-handling.md - Load when defining error handling or creating custom exceptions