CLAUDE.md rules for Python backends and data work with modern type hints, Pydantic v2 response models, 409 handling and pandas code that avoids chained assignment.
.claude/rules/claude-python-developer.md. Downloaded files need to be placed in that repository path.---
paths:
- "**/*"
---
# Python Conventions (Backend and Data)
Applies to: Python code in this repository, including web APIs (FastAPI or Django) and data analysis (pandas/NumPy).
Version baseline: checked against Python 3.10+ syntax (3.15 is the latest release), Pydantic 2, SQLAlchemy 2 and pandas 2.x/3.x. Read `pyproject.toml` for `requires-python` and dependency versions, and don't use syntax or APIs newer than the declared minimum.
## Code standards
- Type-hint every function signature. Use built-in generics and `X | None` (`list[str]`, `dict[str, int]`, `str | None`), not `typing.List`/`Optional` in new code.
- Follow PEP 8. Let the configured formatter and linter (for example `ruff format`, `ruff check`) decide style instead of hand-formatting.
- Give public functions and classes docstrings that state behavior, parameters with constraints, return values and raised exceptions.
- Raise specific exceptions and catch only what you can handle. No bare `except:`, and never `except Exception: pass`.
- Use context managers (`with`, `async with`) for files, locks, sessions and connections.
- Use `dataclasses` (or Pydantic models at I/O boundaries) for structured data, not loose dicts.
## Web APIs (FastAPI)
- Separate input models from output models, and return output models so private columns never leak.
- Use Pydantic v2 APIs: `model_config = ConfigDict(from_attributes=True)`, `model_dump()` and `model_validate()`.
- Use dependency injection for sessions, settings and the current user. With SQLAlchemy 2 async, use one `AsyncSession` per request from `async_sessionmaker(..., expire_on_commit=False)`.
- Map uniqueness violations to 409, and keep a database constraint as the real guard rather than only a pre-check.
- In `async def` endpoints, use async libraries. Call blocking code from a plain `def` endpoint or `run_in_threadpool`.
```python
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, ConfigDict, Field
from app.repositories import UserRepository, get_user_repo # project dependency
class UserCreate(BaseModel):
email: str = Field(max_length=254) # use EmailStr when pydantic[email] is installed
name: str = Field(min_length=1, max_length=100)
class UserResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
email: str
name: str
router = APIRouter(prefix="/users", tags=["users"])
Repo = Annotated[UserRepository, Depends(get_user_repo)]
@router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserCreate, repo: Repo) -> UserResponse:
"""Create a user; 409 if the email is already registered."""
if await repo.email_exists(data.email):
raise HTTPException(status.HTTP_409_CONFLICT, "Email already registered")
user = await repo.create(data) # repository also handles the unique-constraint race
return UserResponse.model_validate(user)
```
## Data analysis (pandas)
- Prefer method chains and vectorized operations over row loops and `iterrows`.
- Parse dates and set dtypes explicitly at load time (`parse_dates=`, `dtype=`), and validate required columns before analysis.
- Don't modify the input DataFrame in place inside reusable functions. Return a new one.
- Never use chained assignment (`df[col][mask] = x`). It stops working under pandas 3 Copy-on-Write. Use `df.loc[mask, col] = x`.
- `count` ignores missing values while `size` counts rows. Choose deliberately.
```python
import pandas as pd
def analyze_sales(df: pd.DataFrame) -> pd.DataFrame:
"""Monthly sales per category: total, mean order value and order count."""
required = {"date", "category", "amount", "id"}
missing = required - set(df.columns)
if missing:
raise ValueError(f"missing columns: {sorted(missing)}")
return (
df.assign(month=lambda x: pd.to_datetime(x["date"]).dt.to_period("M"))
.groupby(["category", "month"], as_index=False)
.agg(total_sales=("amount", "sum"), avg_order=("amount", "mean"), orders=("id", "count"))
)
```
## Tests
- Use pytest with fixtures. Async tests need `pytest-asyncio` or `anyio`. Test APIs with `TestClient` and `app.dependency_overrides`. Test data functions on small hand-built DataFrames with known answers.
## Verify before finishing
Run when available: `ruff check .`, `ruff format --check .`, `mypy` or `pyright` (if configured), and `pytest`.
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Claude
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Claude Code works in a Python repository that has a FastAPI service and pandas reporting code, with this file loaded as a project rule scoped to **/*.py.
Add POST /users (email, name; 201, 409 on duplicate email, never return password_hash) and fix reports/sales.py, which loops with iterrows and does df['amount'][df['amount'] < 0] = 0. Project: requires-python >= 3.11, pydantic 2, pandas 3.
Illustrative; not a recorded model run. Separate UserCreate/UserResponse models with ConfigDict(from_attributes=True); an Annotated dependency for the repository; 409 for a duplicate email, with the unique constraint noted as the real guard; no password_hash in the response; the sales code rewritten as a method chain with groupby/agg, `df.loc[mask, 'amount'] = 0` instead of chained assignment, a required-column check, and no mutation of the input; pytest tests with a tiny DataFrame and known totals; ruff/mypy/pytest results.
Claude Code loads persistent project instructions from CLAUDE.md files and from Markdown rules in .claude/rules/. Rules can be scoped to file paths with a paths frontmatter field, and CLAUDE.md can import other files with @path syntax. The rules in this directory are written as plain instruction prompts: in Claude Code, save them as CLAUDE.md or .claude/rules/ content; in Claude.ai or the Claude API, use the same text as project instructions or a system prompt instead.
.claude/rules/claude-python-developer.mdStarting point, not a tested configuration for your repository. Loaded when Claude Code works with files matching paths. Review the instructions, adapt the file paths and run your project's existing checks.
---
paths:
- "**/*"
---
# Python Conventions (Backend and Data)
Applies to: Python code in this repository, including web APIs (FastAPI or Django) and data analysis (pandas/NumPy).
Version baseline: checked against Python 3.10+ syntax (3.15 is the latest release), Pydantic 2, SQLAlchemy 2 and pandas 2.x/3.x. Read `pyproject.toml` for `requires-python` and dependency versions, and don't use syntax or APIs newer than the declared minimum.
## Code standards
- Type-hint every function signature. Use built-in generics and `X | None` (`list[str]`, `dict[str, int]`, `str | None`), not `typing.List`/`Optional` in new code.
- Follow PEP 8. Let the configured formatter and linter (for example `ruff format`, `ruff check`) decide style instead of hand-formatting.
- Give public functions and classes docstrings that state behavior, parameters with constraints, return values and raised exceptions.
- Raise specific exceptions and catch only what you can handle. No bare `except:`, and never `except Exception: pass`.
- Use context managers (`with`, `async with`) for files, locks, sessions and connections.
- Use `dataclasses` (or Pydantic models at I/O boundaries) for structured data, not loose dicts.
## Web APIs (FastAPI)
- Separate input models from output models, and return output models so private columns never leak.
- Use Pydantic v2 APIs: `model_config = ConfigDict(from_attributes=True)`, `model_dump()` and `model_validate()`.
- Use dependency injection for sessions, settings and the current user. With SQLAlchemy 2 async, use one `AsyncSession` per request from `async_sessionmaker(..., expire_on_commit=False)`.
- Map uniqueness violations to 409, and keep a database constraint as the real guard rather than only a pre-check.
- In `async def` endpoints, use async libraries. Call blocking code from a plain `def` endpoint or `run_in_threadpool`.
```python
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, ConfigDict, Field
from app.repositories import UserRepository, get_user_repo # project dependency
class UserCreate(BaseModel):
email: str = Field(max_length=254) # use EmailStr when pydantic[email] is installed
name: str = Field(min_length=1, max_length=100)
class UserResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
email: str
name: str
router = APIRouter(prefix="/users", tags=["users"])
Repo = Annotated[UserRepository, Depends(get_user_repo)]
@router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserCreate, repo: Repo) -> UserResponse:
"""Create a user; 409 if the email is already registered."""
if await repo.email_exists(data.email):
raise HTTPException(status.HTTP_409_CONFLICT, "Email already registered")
user = await repo.create(data) # repository also handles the unique-constraint race
return UserResponse.model_validate(user)
```
## Data analysis (pandas)
- Prefer method chains and vectorized operations over row loops and `iterrows`.
- Parse dates and set dtypes explicitly at load time (`parse_dates=`, `dtype=`), and validate required columns before analysis.
- Don't modify the input DataFrame in place inside reusable functions. Return a new one.
- Never use chained assignment (`df[col][mask] = x`). It stops working under pandas 3 Copy-on-Write. Use `df.loc[mask, col] = x`.
- `count` ignores missing values while `size` counts rows. Choose deliberately.
```python
import pandas as pd
def analyze_sales(df: pd.DataFrame) -> pd.DataFrame:
"""Monthly sales per category: total, mean order value and order count."""
required = {"date", "category", "amount", "id"}
missing = required - set(df.columns)
if missing:
raise ValueError(f"missing columns: {sorted(missing)}")
return (
df.assign(month=lambda x: pd.to_datetime(x["date"]).dt.to_period("M"))
.groupby(["category", "month"], as_index=False)
.agg(total_sales=("amount", "sum"), avg_order=("amount", "mean"), orders=("id", "count"))
)
```
## Tests
- Use pytest with fixtures. Async tests need `pytest-asyncio` or `anyio`. Test APIs with `TestClient` and `app.dependency_overrides`. Test data functions on small hand-built DataFrames with known answers.
## Verify before finishing
Run when available: `ruff check .`, `ruff format --check .`, `mypy` or `pyright` (if configured), and `pytest`.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Imports with @path can nest up to four hops deep, according to the docs. Claude Code can read AGENTS.md as project instructions without extra configuration, but by default only when there is no CLAUDE.md in the working directory or above it. The docs list this behavior for version 2.1.277 and later and describe a setting (claude-md-and-agents-md) that loads both files. If you maintain AGENTS.md for other tools, you can also import it from CLAUDE.md with @AGENTS.md.
Documentation checked 2026-11-05: Claude Code docs: Manage Claude's memory
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.