Python is one of the most flexible programming languages out there. You can write the same program ten different ways, and technically all of them work. That flexibility is also what makes it hard for Claude to know which way you prefer without being told.
Do you want Django-style class-based views or FastAPI-style function views? Are you using type hints everywhere or just in critical functions? Do you prefer dataclasses or Pydantic models for structured data? Do you test with pytest, unittest, or not at all?
Your CLAUDE.md answers all of these questions upfront, so every session starts with Claude already knowing your preferences.
📋 TL;DR
– Specify your Python version — 3.9, 3.10, 3.11, and 3.12 have different available features
– Define your framework clearly: Django, Flask, FastAPI, or script/library (no framework)
– Explicit type hint requirements make a huge difference in output quality
– Your testing setup (pytest vs unittest, coverage expectations) belongs in CLAUDE.md
– A complete copy-ready template is included at the bottom
This is part of our complete CLAUDE.md — The Complete Beginner’s Guide (2026). If you’re setting up CLAUDE.md for the first time, see How to Create Your First CLAUDE.md File.
Why Python Needs a Specific CLAUDE.md
Python is used for everything — web apps, data science, automation, DevOps scripts, machine learning, CLIs, and APIs. The same language looks completely different depending on the domain.
Without a CLAUDE.md, Claude might:
- Write
print()statements when you uselogging - Use
dictwhen you wantdataclassesor Pydantic - Skip type hints when your whole codebase uses them
- Write
unittest-style tests when you use pytest - Use
os.pathwhen you preferpathlib - Suggest
requirements.txtwhen you use Poetry oruv
These aren’t bugs. Claude is making reasonable choices. But they’re not your choices. A well-written CLAUDE.md makes Claude’s default choices match yours.
Section 1: Python Version and Environment
Start with the basics. Python 3.11 and 3.12 have performance improvements and new syntax (like match statements). If you’re on 3.9, Claude shouldn’t suggest features that don’t exist yet.
## Python Environment
- Python version: 3.11
- Package manager: [pip + requirements.txt / Poetry / uv]
- Virtual environment: [venv / conda / Poetry-managed / uv-managed]
- Python path: `src/` layout (packages under `src/[package_name]/`)
If you’re using Poetry:
## Python Environment
- Python version: 3.12
- Package manager: Poetry (pyproject.toml is the source of truth)
- Adding packages: `poetry add [package]` — never edit pyproject.toml manually
- Dev dependencies: `poetry add --group dev [package]`
If you’re using uv (the fast new package manager):
## Python Environment
- Python version: 3.11
- Package manager: uv
- Adding packages: `uv add [package]`
- Running scripts: `uv run python [script.py]`
- Syncing dependencies: `uv sync`
Section 2: Framework
This is the second most important section. A Django project, a FastAPI project, and a plain Python script project are almost entirely different in their conventions.
For Django:
## Framework: Django 5.x
### Django Patterns
- Use class-based views (CBVs) for CRUD operations — function views for simple cases
- All models go in `[app]/models.py` — one model file per app
- Use Django forms for all form handling — validate at the form layer, not the view
- Migrations: always use `makemigrations` and `migrate` — never edit migration files
- Django ORM only — no raw SQL unless absolutely necessary with `connection.execute()`
- Custom managers for complex querysets — don't chain complex queries in views
- Use `select_related()` and `prefetch_related()` to eliminate N+1 queries
- Django REST Framework for all API endpoints
### Django Project Structure
myproject/
├── myproject/ # Project config
│ ├── settings/
│ │ ├── base.py
│ │ ├── development.py
│ │ └── production.py
│ ├── urls.py
│ └── wsgi.py
├── apps/
│ ├── users/ # User app
│ ├── billing/ # Billing app
│ └── [other apps]
└── manage.py
For FastAPI:
## Framework: FastAPI 0.111.x
### FastAPI Patterns
- Pydantic v2 for all request/response models
- Dependency injection via `Depends()` for auth, db sessions, settings
- Async everywhere: `async def` for route handlers and service functions
- Router-based organization: one `APIRouter` per domain/feature
- Background tasks via `BackgroundTasks` for fire-and-forget operations
- Type-annotated path, query, and body parameters — never use raw `Request`
### FastAPI Project Structure
app/
├── main.py # FastAPI app initialization
├── routers/ # APIRouter modules per domain
│ ├── users.py
│ ├── items.py
│ └── auth.py
├── models/ # SQLAlchemy / database models
├── schemas/ # Pydantic request/response schemas
├── services/ # Business logic layer
├── dependencies/ # Dependency injection functions
└── core/ # Config, database setup, security
For Flask:
## Framework: Flask 3.x
### Flask Patterns
- Application factory pattern (`create_app()` in `__init__.py`)
- Blueprints for organizing routes by feature
- Flask-SQLAlchemy for ORM
- Flask-Login or Flask-JWT-Extended for authentication
- Marshmallow for serialization/deserialization
- Config via environment variables, loaded in `config.py`
### Flask Project Structure
app/
├── __init__.py # Application factory
├── models/ # SQLAlchemy models
├── views/ # Route handlers organized by blueprint
├── forms/ # WTForms form classes
├── schemas/ # Marshmallow schemas
└── utils/ # Helper functions
config.py
run.py
For scripts/automation (no framework):
## Project Type: Python Scripts / Automation
This project is a collection of standalone Python scripts — no web framework.
- Use `argparse` or `click` for CLI argument parsing
- Use `logging` for all output — not `print()` (except for intentional user-facing output)
- Use `pathlib.Path` for all file system operations — not `os.path`
- Use `subprocess.run()` with `check=True` for shell commands
- Error handling: raise specific exceptions, never suppress them silently
Section 3: Type Hints
Type hints in Python are optional but valuable. Define how strictly you use them.
## Type Hints Policy
We use full type hints throughout the codebase:
- All function parameters must have type annotations
- All function return types must be explicit (including `-> None`)
- Use `from __future__ import annotations` at the top of all files for forward references
- Use `Optional[X]` or `X | None` (Python 3.10+ union syntax) for optional values
- Use `TypeVar` and `Generic` for generic containers
- Complex types should use `TypeAlias` for readability
Type checking: mypy with strict mode (`mypy --strict`)
No `Any` from `typing` — use `object` or narrow the type properly
If you use looser typing:
## Type Hints Policy
- Type hints preferred but not required on every function
- Required on: all public functions in library code, all API schema classes
- Optional on: private/internal helpers, test files
- Type checking: not currently running mypy (planned future addition)
Section 4: Code Style and Formatting
## Code Style
### Formatting (enforced by tools)
- Line length: 88 characters (Black default)
- Formatter: Black — run `black .` before committing
- Import sorter: isort (configured to be compatible with Black)
- Linter: Ruff (replaces flake8 + various plugins)
### Python Style Rules
- 4-space indentation (PEP 8 — no tabs)
- Single blank line between methods in a class
- Two blank lines between top-level functions and class definitions
- Follow PEP 8 naming:
- Variables and functions: `snake_case`
- Classes: `PascalCase`
- Constants: `UPPER_SNAKE_CASE`
- Private attributes: `_leading_underscore`
- "Very private" attributes: `__double_leading_underscore`
### Docstrings
- Use Google-style docstrings for all public functions and classes
- One-line docstrings for obvious functions are fine
- Example:
def get_user_by_id(user_id: int) -> User | None:
“””Fetch a user from the database by their ID.
Args:
user_id: The unique identifier for the user.
Returns:
The User object if found, or None if no user exists with that ID.
Raises:
DatabaseConnectionError: If the database is unreachable.
“””
### Prefer These Patterns
- f-strings for string formatting (not `.format()` or `%`)
- `pathlib.Path` for file paths (not `os.path`)
- `dataclasses` or Pydantic for structured data (not plain dicts)
- `logging` for all logging (not `print()`)
- Context managers (`with` statements) for file I/O and connections
- List/dict/set comprehensions when they improve readability
Section 5: Error Handling
## Error Handling
### Rules
- Never use bare `except:` — always catch specific exceptions
- Prefer specific exception types: `ValueError`, `TypeError`, `KeyError`
- Define custom exceptions in `[app]/exceptions.py` for domain errors
- Log exceptions with `logger.exception()` (includes stack trace automatically)
- Don't catch and ignore exceptions without a comment explaining why it's safe
### Pattern for Service Functions
Service functions return data or raise exceptions — they don't return error codes:
Good pattern
def get_user(user_id: int) -> User:
user = db.get(User, user_id)
if user is None:
raise UserNotFoundError(f”User {user_id} does not exist”)
return user
Not our pattern
def get_user(user_id: int) -> tuple[User | None, str | None]:
… # avoid this in service functions
### Logging Setup
- Logger per module: `logger = logging.getLogger(__name__)`
- Log levels: DEBUG for dev info, INFO for significant events, WARNING for unexpected
but handled situations, ERROR for failures, CRITICAL for system-breaking failures
- Never log sensitive data (passwords, tokens, PII)
Section 6: Testing
## Testing
### Setup
- Framework: pytest
- Test discovery: files named `test_[name].py` or `[name]_test.py`
- Location: `/tests/` directory mirroring the source structure
- Coverage: `pytest --cov=[package_name] --cov-report=term-missing`
- Target coverage: 80% minimum on service functions
### Pytest Conventions
- Use fixtures for setup/teardown — not `setUp`/`tearDown` class methods
- Prefer function-scoped fixtures unless sharing is necessary
- Group related tests in classes named `TestClassName` or `TestFunctionName`
- Test names must describe what they test: `test_get_user_returns_none_when_not_found`
### What to Test
- All service/business logic functions
- All data validation functions
- All utility functions
- Edge cases: empty inputs, None values, boundary values
### What Not to Test
- Direct ORM calls without business logic
- Django/FastAPI boilerplate
- Third-party library behavior
### Mocking
- Use `pytest-mock` for mocking — not `unittest.mock` directly
- Mock at the boundary: mock external services, not internal functions
- Use `@pytest.fixture` to set up mocked dependencies
Section 7: Database and Data Layer
## Database
### ORM / Database Access
- Database: PostgreSQL 15
- ORM: SQLAlchemy 2.x (not 1.x — use the new 2.0 syntax)
- Session management: one session per request via dependency injection
- All database access in `[app]/repositories/` or `[app]/db/` — never in views/routes
### SQLAlchemy 2.x Patterns
- Use `select()` syntax, not legacy `session.query()` syntax
- Define models with `DeclarativeBase` from `sqlalchemy.orm`
- Relationships must specify `back_populates`
- All models have `__tablename__` defined explicitly
### Migrations
- Tool: Alembic
- Never edit existing migration files — only generate new ones
- Migration naming: `[action]_[table]_[change].py`
(e.g. `add_created_at_to_users.py`)
- Always include `downgrade()` logic in migrations
### Query Rules
- No N+1 queries — use `joinedload()` or `selectinload()` for relationships
- Large result sets: use `.yield_per()` for pagination, never load all rows at once
- Indexes: always define indexes on foreign keys and commonly-filtered columns
The Full Template
# [Project Name] — Claude Code Instructions
## Project Overview
[What this project does, who uses it, what stage it's at.]
## Python Environment
- Python version: [3.10 / 3.11 / 3.12]
- Package manager: [pip + requirements.txt / Poetry / uv]
- Framework: [Django / FastAPI / Flask / None]
## Coding Standards
- Formatter: Black (line length: 88)
- Linter: Ruff
- Import sorter: isort
- Type checking: mypy [strict / standard / none]
- Type hints: [required everywhere / required on public functions / preferred]
- Docstrings: Google style on all public functions
## Naming Conventions
- Functions/variables: snake_case
- Classes: PascalCase
- Constants: UPPER_SNAKE_CASE
## Folder Structure
[Paste your actual structure here]
## Commands
- Run app: `[your command]`
- Run tests: `pytest`
- Lint: `ruff check .`
- Format: `black .`
- Type check: `mypy [package]/`
- Install deps: `[pip install -r requirements.txt / poetry install / uv sync]`
## Coding Rules
- Never bare `except:` — catch specific exceptions
- `logging` not `print()` for all logging
- `pathlib.Path` not `os.path` for file paths
- f-strings for string formatting
- Dataclasses or Pydantic for structured data — not plain dicts
- All secrets via environment variables
## Testing Rules
- pytest for all tests
- Tests in `/tests/` mirroring source structure
- Fixtures for setup — not setUp/tearDown
## Constraints
- Never modify: [frozen files or folders]
- Always ask before: adding packages to requirements/pyproject.toml
- Never: hardcode credentials, use bare except, use print() for logging
Common Mistakes in Python CLAUDE.md Files
Not specifying the Python version. The match statement (Python 3.10+), tomllib (3.11+), and various typing improvements across versions mean the version number actually changes what code Claude can suggest.
Skipping the framework section. A Django project and a FastAPI project are almost entirely different workflows. Claude needs to know which one you’re in.
Not defining type hint expectations. This is one of the most common points of inconsistency. Half the codebase with type hints and half without is messy. Be explicit.
Leaving out the logging rule. Claude will default to print() if you don’t specify otherwise. If your codebase uses logging, say so explicitly.
Key Takeaways
- Python version matters** — specify it to avoid suggestions for features that don’t exist in your version
- Framework choice is everything** — Django, FastAPI, Flask, and script projects have completely different patterns
- Type hints need an explicit policy** — without one, Claude will be inconsistent
- Specify your toolchain** — Black, Ruff, isort, mypy — Claude adapts its output to match
- Logging vs print() is a silent divergence** — name
loggingexplicitly or Claude defaults toprint()
Next Steps
- CLAUDE.md for Laravel/PHP Projects** — if you also work with PHP
- How to Structure Coding Standards in CLAUDE.md** — go deeper on writing coding rules that actually stick
- How to Add Architecture Notes to CLAUDE.md** — document how your Python services and layers relate to each other
Return to CLAUDE.md — The Complete Beginner’s Guide (2026) for the full picture.