Python Conventions
Idioms
- •Type hints on all function signatures and class attributes
- •Use f-strings for string formatting
- •Prefer
dataclassesfor plain data;pydantic.BaseModelfor validated data - •Use list/dict/set comprehensions over
map/filterwith lambdas - •Use context managers (
with) for resource management - •Use
pathlib.Pathoveros.pathfor filesystem operations - •Prefer
enum.Enumfor fixed sets of values - •Use
__slots__on performance-critical classes
Project Structure
- •Use src layout:
src/<package_name>/with__init__.py - •Project metadata in
pyproject.toml— nosetup.pyorsetup.cfg - •Use
__init__.pyto define the public API of each package - •Scripts and CLI entry points defined in
pyproject.toml - •Configuration (ruff, pytest) lives in
pyproject.toml
Testing
- •Use pytest as the test framework
- •Test files in
tests/mirroringsrc/structure, namedtest_*.py - •Use fixtures for setup/teardown; define shared fixtures in
conftest.py - •Use
@pytest.mark.parametrizefor testing multiple inputs - •Prefer plain
assertstatements — pytest rewrites them for clear output - •Use
pytest.raisesfor exception testing withmatchparameter
Error Handling
- •Raise specific exceptions — never bare
raise Exception(...) - •Define custom exception hierarchies for domain errors
- •Never use bare
except:orexcept Exception:without re-raising - •Use
contextlib.suppressfor intentionally ignored exceptions - •Log exceptions with
logger.exception()to capture tracebacks - •Let unexpected errors propagate — catch only what you can handle
Dependencies
- •Data validation: pydantic
- •HTTP client: httpx (async-native, modern API)
- •Linting/formatting: ruff (replaces flake8 + black + isort)
- •Task runner: just or make for common commands
- •Type checking: pyright or mypy in strict mode
Anti-patterns
- •Mutable default arguments (
def f(x=[])) — useNonewith default in body - •Broad
except Exceptionclauses that swallow errors - •Star imports (
from module import *) — always import explicitly - •Global mutable state — pass dependencies explicitly
- •Using
type: ignorewithout a specific error code - •Nested functions for reusable logic — extract to module-level functions