Best .cursorrules for Python Developers 2026
Production-ready Python rules for Cursor. Modern Python 3.12, FastAPI, Django, and data science — copy and paste into your project today.
Quick Start
Copy the ruleset that matches your stack into .cursorrules in your project root. For FastAPI projects: start with "Modern Python 3.12" + "FastAPI Expert" combined.
Python has evolved significantly — type hints are now standard, Pydantic v2 is the default for data validation, and async patterns are expected in web APIs. These rules reflect where Python development actually is in 2026.
Modern Python 3.12 (Universal)
Core rules for any Python 3.12+ project — type hints, patterns, and style.
You are an expert Python 3.12 developer. Follow modern Python patterns: TYPE HINTS (mandatory): - ALL function parameters and return types must have type hints - Use built-in generics: list[str] not List[str], dict[str, int] not Dict[str, int] - Use X | None instead of Optional[X] (Python 3.10+ union syntax) - Use TypedDict for structured dicts, dataclasses for simple data objects - Use Protocol for structural subtyping instead of ABCs where possible CODE STYLE: - Follow PEP 8 (4-space indentation, 88-char line length with Black) - Use f-strings for all string formatting (not % or .format()) - Use walrus operator (:=) sparingly, only when it genuinely simplifies code - Prefer pathlib.Path over os.path for file operations - Use enumerate() instead of range(len(x)) - Use zip() instead of indexed parallel iteration FUNCTIONS & CLASSES: - Keep functions small and single-purpose (< 20 lines ideal) - Use dataclasses or Pydantic for data containers (no plain dicts for structures) - Use __slots__ in classes with many instances - Use @classmethod for alternative constructors - Use @property for computed attributes ERROR HANDLING: - Catch specific exceptions, never bare except: - Use contextlib.suppress() for expected exceptions - Log exceptions with context (logger.exception() preserves stack trace) - Create custom exception classes for domain errors PERFORMANCE: - Use generators for large data (yield not return list) - Use comprehensions over map/filter for readability - Use collections.Counter, defaultdict, deque appropriately - Profile before optimizing — don't guess
FastAPI Expert
Rules for FastAPI with async/await, Pydantic v2, and REST API best practices.
You are a FastAPI expert. Rules for this FastAPI project: MODELS: - Use Pydantic v2 for all request/response models - Separate request schemas (Input) from response schemas (Output) - Use model_validator for cross-field validation - Never return ORM objects directly — always convert to response schemas - Mark sensitive fields with exclude=True in model_config ENDPOINTS: - Use async def for all endpoint handlers - Group related endpoints with APIRouter and appropriate prefix/tags - Use HTTPException with appropriate status codes (404 not 500 for missing resources) - Use Depends() for dependency injection (auth, DB sessions, rate limiting) - Type all path params, query params, and bodies explicitly ASYNC: - Use async/await consistently — don't mix sync DB calls in async handlers - Use asyncio.gather() for parallel operations - Use httpx.AsyncClient (not requests) for HTTP calls within handlers - Run CPU-bound tasks in thread pool: run_in_executor() SECURITY: - Authenticate via OAuth2PasswordBearer or JWT — never skip auth middleware - Validate all inputs via Pydantic models (automatic with FastAPI) - Use environment variables for all secrets (pydantic-settings) - Rate limit sensitive endpoints DATABASE: - Use SQLAlchemy 2.0 async patterns with asyncpg - Always use transactions for multi-step writes - Use select() syntax not legacy query()
Data Science & ML
Rules for pandas, NumPy, scikit-learn, and Jupyter notebooks.
You are a data science expert. Follow these patterns for data work: PANDAS: - Use .loc[] and .iloc[] for explicit indexing — avoid chained indexing - Always copy DataFrames before modifying: df = df.copy() - Use .assign() for creating new columns (method chaining) - Use .pipe() for applying functions in pipelines - Profile large DataFrames first (df.info(), df.describe()) - Use appropriate dtypes (category for low-cardinality strings) NUMPY: - Vectorize operations — avoid Python loops over arrays - Specify dtypes explicitly when creating arrays (np.float32 vs float64) - Use np.where() for conditional array operations SCIKIT-LEARN: - Always use Pipeline to chain preprocessing + model - Set random_state for reproducibility - Use cross_val_score for evaluation (not a single train/test split) - Scale features before distance-based models (KNN, SVM, neural nets) - Check for data leakage: fit on train only, transform train AND test JUPYTER NOTEBOOKS: - One notebook = one analysis or experiment - Restart kernel and run all before committing - Put reusable functions in .py files, not notebooks - Use %time and %%time for performance checks - Document hypotheses and conclusions in markdown cells
Combining Rulesets
For FastAPI projects:
# .cursorrules [Modern Python 3.12 rules] --- [FastAPI Expert rules]
Keep total length reasonable — under 2,000 tokens for consistent application. If rules are too long, split into named rules files in .cursor/rules/.
What About Django?
For Django projects, add these to the Modern Python base:
DJANGO SPECIFICS: - Use Django ORM — no raw SQL unless absolutely necessary - Use select_related() and prefetch_related() to prevent N+1 queries - Always use get_object_or_404() for user-facing views - Use Django forms for validation in views, not manual validation - Use class-based views for CRUD, function-based for complex logic - Use Django signals sparingly — prefer explicit calls - Use management commands for data migration scripts
Frequently Asked Questions
Do these work with Claude Code SKILL.md too?
Yes — the content is nearly identical. For Claude Code, wrap it in SKILL.md frontmatter and place in .claude/skills/python-expert.md.
Should I include my specific libraries?
Yes — add your specific dependencies. If you use SQLAlchemy 2.0, say so. If you use httpx, say "use httpx for HTTP, not requests". Specificity dramatically improves results.
Using React Instead?
See our React and Next.js rules, or the complete .cursorrules guide.