.cursorrules (deprecated)
rules/python-modern/.cursorrules.cursorrules
Quality
88/100
Scores the file, not the repository.Length
896 words
15 headings · 12 code blocksRepository
16
— · pushed 108 days agoLast changed
2 days ago
First indexed 2 days ago.1# Modern Python 3.12+ — Cursor Rules2# Production Python with type hints, dataclasses, modern patterns, and strict quality34# Project Context5You are writing modern Python 3.12+. The project uses type hints throughout, leverages6dataclasses and Pydantic for data modeling, follows PEP standards strictly, and uses7modern Python features including match statements, type parameter syntax, and f-strings.89# Type Hints (Mandatory)10- Type ALL function signatures: parameters and return values.11- Use built-in generic types (Python 3.9+): `list[str]`, `dict[str, int]`, `tuple[int, ...]`.12- DON'T: Import `List`, `Dict`, `Tuple`, `Set` from `typing` — use builtins.13- Use the `|` union syntax (Python 3.10+): `str | None` instead of `Optional[str]`.14- Use `type` statement for type aliases (Python 3.12+):15```python16 type UserId = int17 type UserMap = dict[str, User]18 type Callback[T] = Callable[[T], None] # generic alias19```20- Use `Self` type (Python 3.11+) for methods returning the same class:21```python22 from typing import Self23 class Builder:24 def set_name(self, name: str) -> Self:25 self.name = name26 return self27```28- Use `TypeGuard` for type-narrowing functions:29```python30 def is_valid_user(data: dict) -> TypeGuard[UserDict]:31 return 'id' in data and 'email' in data32```3334# Dataclass Patterns35- Use `@dataclass` for data containers. Use `@dataclass(frozen=True)` for immutables.36- Use `@dataclass(slots=True)` for better memory and attribute access performance.37- Use `field(default_factory=list)` for mutable defaults — never `field(default=[])`.38- Use `__post_init__` for validation:39```python40 @dataclass(frozen=True, slots=True)41 class Temperature:42 celsius: float43 def __post_init__(self) -> None:44 if self.celsius < -273.15:45 raise ValueError("Temperature below absolute zero")46```47- Use `kw_only=True` (Python 3.10+) when fields are numerous to force keyword arguments.4849# Match Statements (Structural Pattern Matching)50- Use `match` statements for complex conditional logic with destructuring:51```python52 match command:53 case {"action": "create", "data": data}:54 return create_item(data)55 case {"action": "delete", "id": int(item_id)}:56 return delete_item(item_id)57 case {"action": str(action)}:58 raise ValueError(f"Unknown action: {action}")59 case _:60 raise TypeError("Invalid command format")61```62- Prefer match over long if/elif chains when checking structure or type.63- Use guard clauses with `if`: `case Point(x, y) if x > 0 and y > 0:`.6465# Exception Handling66- Use exception groups (Python 3.11+) for concurrent error handling:67```python68 try:69 results = await asyncio.gather(*tasks, return_exceptions=True)70 except* ValueError as eg:71 handle_value_errors(eg.exceptions)72 except* ConnectionError as eg:73 handle_connection_errors(eg.exceptions)74```75- Create custom exception hierarchies with `__init__` typing:76```python77 class AppError(Exception):78 def __init__(self, message: str, code: str, *, context: dict | None = None) -> None:79 super().__init__(message)80 self.code = code81 self.context = context or {}82```83- Use `raise ... from e` to chain exceptions and preserve context.84- DON'T: Catch bare `Exception` — catch specific exceptions.85- DON'T: Use `except: pass` — always handle or log the error.8687# Async Patterns88- Use `async`/`await` for all I/O-bound operations.89- Use `asyncio.TaskGroup` (Python 3.11+) for structured concurrency:90```python91 async with asyncio.TaskGroup() as tg:92 task1 = tg.create_task(fetch_users())93 task2 = tg.create_task(fetch_products())94 users = task1.result()95 products = task2.result()96```97- Use `asyncio.timeout()` (Python 3.11+) instead of `asyncio.wait_for`:98```python99 async with asyncio.timeout(10):100 data = await slow_operation()101```102- DON'T: Mix sync and async code without `asyncio.to_thread()`.103- DON'T: Use `asyncio.gather()` without handling individual task exceptions.104105# String Formatting106- Always use f-strings for string interpolation. Never use `%` formatting or `.format()`.107- Use `=` in f-strings for debugging: `f"{variable=}"` prints `variable=value`.108- For multi-line strings, use dedented triple-quoted f-strings.109- DON'T: Concatenate strings with `+` in loops — use `"".join()`.110111# Comprehensions and Generators112- Use list/dict/set comprehensions for simple transformations.113- Use generator expressions for large sequences to save memory:114```python115 total = sum(item.price for item in items if item.in_stock)116```117- DON'T: Nest more than 2 levels of comprehensions — use a for loop instead.118- Use `itertools` for complex iteration patterns (chain, islice, groupby, product).119120# File and Path Operations121- Use `pathlib.Path` exclusively — never `os.path`:122```python123 config_path = Path(__file__).parent / "config" / "settings.json"124 content = config_path.read_text(encoding="utf-8")125```126- Use context managers for file operations: `with open(...) as f:`.127- Always specify encoding: `encoding="utf-8"`.128129# Project Standards130- Use `ruff` for linting and formatting (replaces black, isort, flake8).131- Use `mypy` with strict mode for type checking.132- Use `pytest` for testing with `pytest-cov` for coverage.133- Use `pyproject.toml` for all project configuration (not setup.py/setup.cfg).134- Structure imports: stdlib, third-party, local (ruff handles this).135136# Naming Conventions137- Variables and functions: `snake_case`138- Classes: `PascalCase`139- Constants: `UPPER_SNAKE_CASE`140- Private members: `_single_leading_underscore`141- Module-level dunder: `__all__`, `__version__`142- Type aliases: `PascalCase` (they represent types)143- Boolean variables: `is_`, `has_`, `should_`, `can_` prefix144145# Testing146- Use `pytest` with fixtures, parametrize, and markers.147- Type test fixtures and use factories for test data.148- Use `pytest.raises` with `match` parameter for exception testing:149```python150 with pytest.raises(ValueError, match="Temperature below"):151 Temperature(celsius=-300)152```153- Use `tmp_path` fixture for file system tests.154- Use `monkeypatch` for environment variables and module-level patches.155- Aim for: business logic 95%+, utilities 100%, integration 80%+.156157# Common Mistakes to Avoid158- DON'T: Use mutable default arguments: `def f(items: list = [])` — use `None` and create inside.159- DON'T: Use `type()` for type checking — use `isinstance()`.160- DON'T: Use `is` to compare values — use `==`. (`is` compares identity, not equality.)161- DON'T: Import with wildcard: `from module import *`.162- DON'T: Use global variables for state — pass dependencies explicitly.163- DON'T: Ignore `mypy` errors with `# type: ignore` without a specific error code.164- DON'T: Use `dict.keys()` in membership tests — just use `key in dict`.165
Also in survivorforge/cursor-rules
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| survivorforge/cursor-rulesrules/aws-serverless/.cursorrules · 16 | .cursorrules | teststylearchtypes+6 | 73/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/ai-ml-python/.cursorrules · 16 | .cursorrules | teststylearchdeployment+2 | 81/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/api-design-rest/.cursorrules · 16 | .cursorrules | lint-formatstylesecurityapi+3 | 69/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/api-microservices/.cursorrules · 16 | .cursorrules | buildteststylearch+5 | 92/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/chrome-extension/.cursorrules · 16 | .cursorrules | teststylearchtesting-strategy+4 | 81/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/clean-code/.cursorrules · 16 | .cursorrules | styledo-notagent-behaviourdocs | 57/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/database-sql/.cursorrules · 16 | .cursorrules | styletypessecuritydatabase+3 | 65/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/devops-docker/.cursorrules · 16 | .cursorrules | setupbuildteststyle+4 | 93/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/devops-infrastructure/.cursorrules · 16 | .cursorrules | buildteststylesecurity+3 | 93/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/django-rest/.cursorrules · 16 | .cursorrules | buildteststylearch+5 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/docker-devops/.cursorrules · 16 | .cursorrules | setupteststylearch+6 | 85/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/flutter-dart/.cursorrules · 16 | .cursorrules | teststylearchtypes+5 | 89/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/fullstack-nextjs-prisma/.cursorrules · 16 | .cursorrules | teststylearchtypes+7 | 96/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/go-gin/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+5 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/go-production/.cursorrules · 16 | .cursorrules | teststylearchtesting-strategy+3 | 89/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/golang-api/.cursorrules · 16 | .cursorrules | buildteststylearch+6 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/langchain-ai/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+4 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/mcp-server/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+7 | 68/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/mern-stack/.cursorrules · 16 | .cursorrules | setupteststylearch+6 | 81/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/mobile-react-native/.cursorrules · 16 | .cursorrules | teststylearchtypes+7 | 89/100 | 2 days ago |
Diff against rules/aws-serverless/.cursorrules Diff against rules/ai-ml-python/.cursorrules Diff against rules/api-design-rest/.cursorrules Diff against rules/api-microservices/.cursorrules Diff against rules/chrome-extension/.cursorrules Diff against rules/clean-code/.cursorrules Diff against rules/database-sql/.cursorrules Diff against rules/devops-docker/.cursorrules Diff against rules/devops-infrastructure/.cursorrules Diff against rules/django-rest/.cursorrules Diff against rules/docker-devops/.cursorrules Diff against rules/flutter-dart/.cursorrules Diff against rules/fullstack-nextjs-prisma/.cursorrules Diff against rules/go-gin/.cursorrules Diff against rules/go-production/.cursorrules Diff against rules/golang-api/.cursorrules Diff against rules/langchain-ai/.cursorrules Diff against rules/mcp-server/.cursorrules Diff against rules/mern-stack/.cursorrules Diff against rules/mobile-react-native/.cursorrules
