Cursor rule for PEP 8 style and type hints with correct blank-line rules, built-in generics, explicit X | None, mutable-default fixes and formatter-driven checks.
.cursor/rules/python-pep8-and-type-hinting.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for PEP 8 style and type hints with correct blank-line rules, built-in generics, explicit X | None, mutable-default fixes and formatter-driven checks."
globs: "**/*"
alwaysApply: false
---
# Python PEP 8 Style and Type Hinting
Applies to: all Python source in the project (application code, scripts and tests).
Version baseline: checked against PEP 8, PEP 484/585/604 and the Python 3.15 `typing` docs. The examples need Python 3.10+ (`X | None`). Read `requires-python` and the project's formatter, linter and type-checker configuration in `pyproject.toml`. Project configuration wins over this file (for example a line length of 88 or 100).
## Formatting: let the tools decide
- Use the formatter and linter the project already configures (for example ruff format/black plus ruff/flake8) and do not hand-format against them. If none is configured, follow PEP 8 defaults.
- Indent with 4 spaces, never tabs.
- PEP 8 blank lines: two blank lines around top-level function and class definitions, one blank line between methods inside a class.
- PEP 8 limits lines to 79 characters (72 for comments and docstrings). Teams may agree on up to 99. Use the configured value.
- Spaces around assignment and comparison operators (`a = b + 1`), but none around `=` for keyword arguments or unannotated defaults (`f(x=1)`). With an annotation, use spaces: `def f(x: int = 1)`.
## Naming
- `snake_case` for functions, variables, methods and modules. `CapWords` for classes and type variables (`UserId`, `T`). `UPPER_SNAKE_CASE` for module-level constants.
- A leading underscore marks internal names (`_parse_row`). Do not shadow built-ins (`list`, `id`, `type`, `input`, `len`). If a name is unavoidable, use a trailing underscore (`type_`).
## Type hints
- Annotate every public function's parameters and return type, including `-> None`. Annotate module-level constants and class attributes when the type is not obvious.
- Do not annotate every local variable. Annotate a local only when the checker cannot infer it (for example an empty container: `seen: set[str] = set()`).
- Use built-in generics (`list[str]`, `dict[str, int]`, `tuple[int, ...]`) instead of the deprecated `typing.List`/`typing.Dict` aliases. Import abstract types from `collections.abc` (`Iterable`, `Mapping`, `Callable`).
- Write optional values as `str | None` (3.10+) or `Optional[str]` on older versions. A default of `None` does not make a parameter optional by itself: `def f(name: str = None)` is a type error under current checkers.
- Prefer precise types to `Any`. Use `object` when any value is accepted and you will not call methods on it.
```python
from collections.abc import Iterable
MAX_RETRIES: int = 3
def normalize_names(
names: Iterable[str], *, prefix: str | None = None
) -> list[str]:
"""Return stripped, non-empty names, optionally prefixed."""
cleaned = [name.strip() for name in names if name.strip()]
if prefix is None:
return cleaned
return [f"{prefix}{name}" for name in cleaned]
class NameRegistry:
"""Collects unique names."""
def __init__(self) -> None:
self._names: set[str] = set()
def add(self, name: str) -> bool:
"""Add a name; return False if it was already present."""
if name in self._names:
return False
self._names.add(name)
return True
```
## Error handling
- Catch the most specific exception you can handle. Never write a bare `except:`. Avoid `except Exception:` unless you log and re-raise, or you are at a top-level boundary.
- Chain exceptions when translating them: `raise ConfigError("bad port") from exc`.
- Keep `try` blocks small, so that only the call that can fail is inside.
## Common pitfalls
- Mutable default arguments are shared between calls. Use `None` and create the object inside the function:
```python
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
tags = [] if tags is None else tags
tags.append(tag)
return tags
```
- Remove unused imports and variables (the linter's F401/F841 rules or equivalent).
- Extract duplicated logic into a function once it appears a third time, or sooner if the copies must stay consistent.
## Tests
- Write tests with the project's framework (pytest or unittest). Cover expected behaviour, edge cases (empty input, `None`) and error paths.
## Verify before finishing
- Run the configured tools on changed files, for example `ruff check . && ruff format --check .` (or `black --check` + `flake8`), and `mypy` or `pyright` with the project's settings.
- Fix reported issues instead of adding `# noqa` or `# type: ignore`. When suppression is unavoidable, scope it to one code and explain why.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A developer asks Cursor to clean up an older Python module so it passes the project's linter and type checker, without fighting the configured formatter.
Tidy utils.py: it uses from typing import List, Dict, has def add_tag(tag, tags=[]), def load(name: str = None), a bare except:, and a variable named list. Project uses ruff (line-length 88) and mypy; requires-python >= 3.11.
Illustrative; not a recorded model run. A diff that replaces typing.List/Dict with list/dict and adds full signatures with return types. add_tag uses a None default with a new list created inside, and load becomes name: str | None = None. The bare except is narrowed to a specific exception, with raise ... from exc where it translates errors. The shadowed name list is renamed, and blank lines follow PEP 8 (two around top-level definitions, one between methods). The answer reports the output of ruff check, ruff format --check and mypy, with no new noqa or type: ignore.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/python-pep8-and-type-hinting.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Python PEP8 And Type Hinting: Correct Style Rules and Modern Annotations project conventions"
globs: "**/*"
alwaysApply: false
---
# Python PEP 8 Style and Type Hinting
Applies to: all Python source in the project (application code, scripts and tests).
Version baseline: checked against PEP 8, PEP 484/585/604 and the Python 3.15 `typing` docs. The examples need Python 3.10+ (`X | None`). Read `requires-python` and the project's formatter, linter and type-checker configuration in `pyproject.toml`. Project configuration wins over this file (for example a line length of 88 or 100).
## Formatting: let the tools decide
- Use the formatter and linter the project already configures (for example ruff format/black plus ruff/flake8) and do not hand-format against them. If none is configured, follow PEP 8 defaults.
- Indent with 4 spaces, never tabs.
- PEP 8 blank lines: two blank lines around top-level function and class definitions, one blank line between methods inside a class.
- PEP 8 limits lines to 79 characters (72 for comments and docstrings). Teams may agree on up to 99. Use the configured value.
- Spaces around assignment and comparison operators (`a = b + 1`), but none around `=` for keyword arguments or unannotated defaults (`f(x=1)`). With an annotation, use spaces: `def f(x: int = 1)`.
## Naming
- `snake_case` for functions, variables, methods and modules. `CapWords` for classes and type variables (`UserId`, `T`). `UPPER_SNAKE_CASE` for module-level constants.
- A leading underscore marks internal names (`_parse_row`). Do not shadow built-ins (`list`, `id`, `type`, `input`, `len`). If a name is unavoidable, use a trailing underscore (`type_`).
## Type hints
- Annotate every public function's parameters and return type, including `-> None`. Annotate module-level constants and class attributes when the type is not obvious.
- Do not annotate every local variable. Annotate a local only when the checker cannot infer it (for example an empty container: `seen: set[str] = set()`).
- Use built-in generics (`list[str]`, `dict[str, int]`, `tuple[int, ...]`) instead of the deprecated `typing.List`/`typing.Dict` aliases. Import abstract types from `collections.abc` (`Iterable`, `Mapping`, `Callable`).
- Write optional values as `str | None` (3.10+) or `Optional[str]` on older versions. A default of `None` does not make a parameter optional by itself: `def f(name: str = None)` is a type error under current checkers.
- Prefer precise types to `Any`. Use `object` when any value is accepted and you will not call methods on it.
```python
from collections.abc import Iterable
MAX_RETRIES: int = 3
def normalize_names(
names: Iterable[str], *, prefix: str | None = None
) -> list[str]:
"""Return stripped, non-empty names, optionally prefixed."""
cleaned = [name.strip() for name in names if name.strip()]
if prefix is None:
return cleaned
return [f"{prefix}{name}" for name in cleaned]
class NameRegistry:
"""Collects unique names."""
def __init__(self) -> None:
self._names: set[str] = set()
def add(self, name: str) -> bool:
"""Add a name; return False if it was already present."""
if name in self._names:
return False
self._names.add(name)
return True
```
## Error handling
- Catch the most specific exception you can handle. Never write a bare `except:`. Avoid `except Exception:` unless you log and re-raise, or you are at a top-level boundary.
- Chain exceptions when translating them: `raise ConfigError("bad port") from exc`.
- Keep `try` blocks small, so that only the call that can fail is inside.
## Common pitfalls
- Mutable default arguments are shared between calls. Use `None` and create the object inside the function:
```python
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
tags = [] if tags is None else tags
tags.append(tag)
return tags
```
- Remove unused imports and variables (the linter's F401/F841 rules or equivalent).
- Extract duplicated logic into a function once it appears a third time, or sooner if the copies must stay consistent.
## Tests
- Write tests with the project's framework (pytest or unittest). Cover expected behaviour, edge cases (empty input, `None`) and error paths.
## Verify before finishing
- Run the configured tools on changed files, for example `ruff check . && ruff format --check .` (or `black --check` + `flake8`), and `mypy` or `pyright` with the project's settings.
- Fix reported issues instead of adding `# noqa` or `# type: ignore`. When suppression is unavoidable, scope it to one code and explain why.
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.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.