---
name: python-programming
description: Use when writing, reviewing, refactoring or debugging Python code - new modules, scripts or CLIs, type hints, dataclasses and data modelling, error handling, asyncio, pytest tests, project setup with pyproject.toml, tooling (uv, ruff, mypy, pyright), or performance work. Triggers - "write a Python function or class", "add type hints", "make this more Pythonic", "refactor this module", "why is this slow", "set up a Python project", "write tests for this", import or packaging errors, mutable default arguments, async bugs.
---

# Python Programming

Write Python that a reader can follow top to bottom and a type checker can
verify. Most defects in Python code are things a checker or a test would have
caught, so the habit that pays is making them able to catch it.

**Match the project first.** Before writing, read `pyproject.toml` (or
`setup.cfg`, `requirements*.txt`) for the Python version, formatter, linter and
test runner, and look at two existing modules for naming and layout. The
project's conventions win over the defaults below.

## Defaults for new code

Target Python 3.11 or later unless the project says otherwise.

| Decision | Default | Instead of |
|---|---|---|
| Project and dependencies | `pyproject.toml`, `uv` for environments and locking | `setup.py`, bare `requirements.txt` |
| Layout | `src/<package>/`, `tests/` beside it | package at the repository root |
| Format and lint | `ruff format` and `ruff check` | separate black, isort, flake8 |
| Types | built-in generics (`list[str]`), `X \| None`, `collections.abc` for parameters | `typing.List`, `Optional`, `Union` |
| Records | `@dataclass(frozen=True, slots=True)` | dicts with string keys, hand-written `__init__` |
| Untrusted input | Pydantic model at the boundary | manual `isinstance` chains |
| Fixed choices | `enum.StrEnum` | string constants |
| Paths | `pathlib.Path` | `os.path` string joins |
| Time | `datetime.now(UTC)`, always timezone-aware | `datetime.utcnow()` (deprecated, returns naive) |
| Concurrency (I/O) | `asyncio.TaskGroup`, `asyncio.timeout` | bare `gather`, manual task bookkeeping |
| Concurrency (CPU) | `ProcessPoolExecutor`, or vectorize | threads |
| Config | `tomllib`, environment variables, typed settings object | globals, `eval` |
| Logging | `logging.getLogger(__name__)`, `%s` arguments | `print`, f-strings in log calls |
| Tests | `pytest`, plain `assert`, `tmp_path`, `monkeypatch` | `unittest.TestCase` boilerplate |

## Types

- Annotate every function signature. Annotate locals only where inference fails.
- Accept the widest type that works (`Iterable[str]`, `Mapping[str, int]`), return
  the narrowest (`list[str]`). Callers stay flexible and get precise results.
- Use `Protocol` for "anything with this method" instead of a base class the
  caller must inherit from.
- `Any` switches the checker off for everything it touches. Prefer `object` for
  "anything", and narrow with `isinstance` or `match`.
- Make illegal states unrepresentable: an enum or a union of dataclasses beats a
  status string plus optional fields that are only valid together.

## Choosing a data container

| Need | Use |
|---|---|
| Internal record with behaviour | `@dataclass(frozen=True, slots=True)` |
| Parsing and validating external data (JSON, env, user input) | Pydantic model |
| Describing the shape of a dict you do not control | `TypedDict` |
| Small immutable tuple with names | `NamedTuple` |
| Closed set of values | `StrEnum` / `Enum` |

## Errors

- Raise specific exceptions with a message that names the offending value. Define
  one base exception per package so callers can catch the package's errors.
- Catch only what you can handle, at the level that can handle it. `except
  Exception: pass` hides the bug and the next person's afternoon.
- Chain with `raise NewError(...) from err` so the original traceback survives.
- Validate at the boundary (API handler, CLI, file loader), then trust types inside.
- Use context managers for anything that must be released.

## Async

- Async helps with many concurrent waits (network, disk). It does nothing for CPU
  work, and one blocking call (`time.sleep`, `requests.get`, a heavy loop) stalls
  every task. Push blocking work to `asyncio.to_thread`.
- Start concurrent work in a `TaskGroup`: if one task fails the rest are
  cancelled and the error surfaces. A task created and not awaited can vanish
  with its exception.
- Put a timeout on every external call, and bound concurrency with a `Semaphore`.

## Tests

- Test behaviour through the public interface. Tests that mirror the
  implementation break on every refactor and catch nothing.
- One reason to fail per test; name it after the behaviour
  (`test_rejects_negative_quantity`).
- `pytest.mark.parametrize` for input tables, fixtures for setup, `tmp_path` for
  files, `monkeypatch` for environment and attributes.
- Mock at the boundary you do not own (network, clock, filesystem), and patch
  where the name is looked up, not where it is defined.
- A bug fix starts with a test that fails for the reported reason.

## Performance

Measure before changing anything: `python -m cProfile -s cumtime script.py`, or
`py-spy` on a running process. Then, in order of payoff:

1. A better algorithm or data structure (`set` and `dict` lookups, not list scans).
2. Fewer round trips: batch queries and I/O.
3. Vectorize numeric work with NumPy, pandas or Polars.
4. Cache pure functions (`functools.cache`).
5. Processes for CPU-bound work; native code last.

Generators keep memory flat for large streams; lists are faster for small ones.

## Gotchas

| Trap | What happens | Fix |
|---|---|---|
| `def f(x, items=[])` | the default list is shared across calls | `items: list \| None = None`, create inside |
| Closures in a loop (`lambda: i`) | all see the final `i` | bind it: `lambda i=i: i` |
| `is` for value comparison | works for small ints and some strings by accident | `==` for values, `is` only for `None` and sentinels |
| Modifying a list while iterating it | skipped elements | iterate over a copy or build a new list |
| Naive datetimes | silent errors across time zones and DST | timezone-aware everywhere, convert at the edge |
| Floats for money | `0.1 + 0.2 != 0.3` | `Decimal` or integer minor units |
| `except:` or broad `except Exception` | swallows `KeyboardInterrupt` or real bugs | catch the specific error |
| Circular imports | `ImportError` or partially initialised modules | move shared types to a third module; import inside the function as a last resort |
| Opening files without `with` | leaked handles | context manager |

## Before calling it done

```bash
ruff format . && ruff check . --fix
mypy src            # or: pyright
pytest -q
```

Run them and read the output. If the project has no configuration for one of
these, say so instead of inventing a passing result.

## References

| File | When |
|---|---|
| `references/patterns.md` | worked examples: dataclasses, Protocol, StrEnum with match, error chaining, context managers, TaskGroup with timeout and bounded concurrency, pytest patterns |
| `references/project-setup.md` | pyproject.toml template, uv commands, ruff and mypy configuration, pre-commit, CI |
