---
paths:
  - "**/*.py"
  - "**/*.pyi"
---
# Python Patterns

> This file extends [common/patterns.md](../common/patterns.md) with Python specific content.

## Protocol (Duck Typing)

```python
from typing import Protocol

class Repository(Protocol):
    def find_by_id(self, id: str) -> dict | None: ...
    def save(self, entity: dict) -> dict: ...
```

## Dataclasses as DTOs

```python
from dataclasses import dataclass

@dataclass
class CreateUserRequest:
    name: str
    email: str
    age: int | None = None
```

## Context Managers & Generators

- Use context managers (`with` statement) for resource management
- Use generators for lazy evaluation and memory-efficient iteration

## Performance Anti-Patterns

Avoid these in Python services:

- **Sync I/O in async handlers**: blocking DB/HTTP calls inside `async def` FastAPI/Django routes — use `await` with async drivers
- **Missing connection pooling**: configure `pool_size` and `max_overflow` in SQLAlchemy; never create a new engine per request
- **Heavy computation in request handlers**: offload to Celery background tasks or `asyncio.run_in_executor`
- **Missing cache on expensive queries**: wrap slow aggregations with Redis (e.g., `aiocache` or `fastapi-cache`)
- **Loading full querysets when only counts or IDs needed**: use `.values_list()` / `.scalar()` instead of full ORM objects

## Reference

See skill: `python-patterns` for comprehensive patterns including decorators, concurrency, and package organization.
