Cursor rule for advanced Python typing with X | None, PEP 695 generics, Protocols, Literal, TypedDict with NotRequired, TypeIs and strict type checking.
.cursor/rules/python-type-hints-best-practices.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for advanced Python typing with X | None, PEP 695 generics, Protocols, Literal, TypedDict with NotRequired, TypeIs and strict type checking."
globs: "**/*"
alwaysApply: false
---
# Python Type Hints Best Practices
Applies to: Python code checked by a static type checker (mypy or pyright/basedpyright), especially library code and module boundaries.
Version baseline: checked against the Python 3.15 `typing` documentation and the typing specification. Each feature notes the Python version it needs. Read `requires-python`. On older targets, import backports from `typing_extensions` if the project already depends on it.
## Signatures first
- Annotate every function and method signature, including `-> None`. Locals are usually inferred, so annotate them only when inference fails (empty containers, a `None` that is filled later).
- Accept abstract types and return concrete ones: parameters `Iterable[str]` / `Mapping[str, int]` / `Sequence[T]` from `collections.abc`, return `list[str]` / `dict[str, int]`.
## Optional and unions
- Write `X | None` (3.10+) or `Optional[X]`. `Optional` means "may be None", not "may be omitted". A parameter is optional only if it has a default.
- Use unions for real alternatives (`int | str`), and narrow them before use with `isinstance`, `is None` checks or `match`.
- Avoid `Any`. It disables checking for everything it touches. Use `object` for "anything, used opaquely" and a precise type everywhere else.
## Generics
On 3.12+, use PEP 695 syntax. On older targets, use `TypeVar`:
```python
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T | None: # 3.12+
return items[0] if items else None
type Pair[K, V] = tuple[K, V] # 3.12+ type alias statement
```
```python
from typing import TypeVar
T = TypeVar("T")
def first_legacy(items: Sequence[T]) -> T | None: # pre-3.12 equivalent
return items[0] if items else None
```
Add a bound or constraints when the body needs specific operations: `def biggest[T: (int, float)](xs: Sequence[T]) -> T` (constraints), or bound `T` to a Protocol you define (`def close_all[T: SupportsClose](...)` / `TypeVar("T", bound=SupportsClose)`).
## Protocols for structural typing
```python
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
def shutdown(resources: list[SupportsClose]) -> None:
for r in resources:
r.close()
```
- Use a `Protocol` when callers should not need to inherit from your class. Use an ABC when you need shared implementation or runtime registration.
- `@runtime_checkable` only lets `isinstance` check that the methods exist, not their signatures. Do not rely on it for validation.
## Literal, Final and enums
- Use `Literal["asc", "desc"]` for small fixed string or int options in signatures. Use `enum.Enum`/`StrEnum` (3.11+) when the values need behaviour or iteration.
- Mark constants that must not be reassigned with `Final`.
## TypedDict for dict-shaped data
```python
from typing import NotRequired, TypedDict
class UserPayload(TypedDict):
id: int
email: str
nickname: NotRequired[str] # key may be absent (3.11+)
```
- Use `TypedDict` for JSON-like dicts you do not control (API payloads, JSON config). Use a dataclass or Pydantic model when you own the type and want attribute access or validation.
- `TypedDict` does no runtime validation. `UserPayload(**data)` accepts anything. Validate untrusted data separately.
## Narrowing helpers
- Write user-defined type guards with `TypeIs` (3.13+, narrows in both branches) and use `TypeGuard` only when the narrowed type is not a subtype of the input.
- Use `typing.assert_never(x)` in the final `else`/`case _` of an exhaustive match over a union or enum.
## Other useful features
- `Self` (3.11+) for methods returning their own class. `@override` (3.12+) on methods that override a base class method. `Callable[[int], str]` or a callback `Protocol` for functions.
## Checking
- Run the project's checker in its configured mode, for example `mypy --strict src/` or `pyright` with `"typeCheckingMode": "strict"`. New code should introduce no new errors.
- Do not silence errors with `cast(...)` or `# type: ignore` unless you add a comment explaining why. Prefer `# type: ignore[code]` with the specific error code.
## Verify before finishing
- Type checker passes on changed files. Public functions have complete signatures. No new bare `Any` appears in public APIs.
- Run the tests too. Type hints are not enforced at runtime.
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
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A team is tightening typing on a Python library and asks Cursor to annotate a module so it passes mypy --strict without leaning on Any.
Annotate storage/cache.py for mypy --strict. get_first(items) returns the first element or None. close_all(resources) calls .close() on objects from three unrelated libraries. load_user() returns the parsed JSON dict {'id', 'email', optional 'nickname'}. requires-python >= 3.12.Illustrative; not a recorded model run. get_first uses PEP 695 syntax (def get_first[T](items: Sequence[T]) -> T | None). close_all takes a SupportsClose Protocol instead of a union of library classes. load_user returns a TypedDict with NotRequired[str] for nickname and validates at the boundary, because TypedDict does not validate at runtime. There is no Any in the public signatures and no unexplained # type: ignore. The answer ends with the mypy --strict command.
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-type-hints-best-practices.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 Type Hints Best Practices: Generics, Protocols, TypedDict, TypeIs and Strict Checking project conventions"
globs: "**/*"
alwaysApply: false
---
# Python Type Hints Best Practices
Applies to: Python code checked by a static type checker (mypy or pyright/basedpyright), especially library code and module boundaries.
Version baseline: checked against the Python 3.15 `typing` documentation and the typing specification. Each feature notes the Python version it needs. Read `requires-python`. On older targets, import backports from `typing_extensions` if the project already depends on it.
## Signatures first
- Annotate every function and method signature, including `-> None`. Locals are usually inferred, so annotate them only when inference fails (empty containers, a `None` that is filled later).
- Accept abstract types and return concrete ones: parameters `Iterable[str]` / `Mapping[str, int]` / `Sequence[T]` from `collections.abc`, return `list[str]` / `dict[str, int]`.
## Optional and unions
- Write `X | None` (3.10+) or `Optional[X]`. `Optional` means "may be None", not "may be omitted". A parameter is optional only if it has a default.
- Use unions for real alternatives (`int | str`), and narrow them before use with `isinstance`, `is None` checks or `match`.
- Avoid `Any`. It disables checking for everything it touches. Use `object` for "anything, used opaquely" and a precise type everywhere else.
## Generics
On 3.12+, use PEP 695 syntax. On older targets, use `TypeVar`:
```python
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T | None: # 3.12+
return items[0] if items else None
type Pair[K, V] = tuple[K, V] # 3.12+ type alias statement
```
```python
from typing import TypeVar
T = TypeVar("T")
def first_legacy(items: Sequence[T]) -> T | None: # pre-3.12 equivalent
return items[0] if items else None
```
Add a bound or constraints when the body needs specific operations: `def biggest[T: (int, float)](xs: Sequence[T]) -> T` (constraints), or bound `T` to a Protocol you define (`def close_all[T: SupportsClose](...)` / `TypeVar("T", bound=SupportsClose)`).
## Protocols for structural typing
```python
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
def shutdown(resources: list[SupportsClose]) -> None:
for r in resources:
r.close()
```
- Use a `Protocol` when callers should not need to inherit from your class. Use an ABC when you need shared implementation or runtime registration.
- `@runtime_checkable` only lets `isinstance` check that the methods exist, not their signatures. Do not rely on it for validation.
## Literal, Final and enums
- Use `Literal["asc", "desc"]` for small fixed string or int options in signatures. Use `enum.Enum`/`StrEnum` (3.11+) when the values need behaviour or iteration.
- Mark constants that must not be reassigned with `Final`.
## TypedDict for dict-shaped data
```python
from typing import NotRequired, TypedDict
class UserPayload(TypedDict):
id: int
email: str
nickname: NotRequired[str] # key may be absent (3.11+)
```
- Use `TypedDict` for JSON-like dicts you do not control (API payloads, JSON config). Use a dataclass or Pydantic model when you own the type and want attribute access or validation.
- `TypedDict` does no runtime validation. `UserPayload(**data)` accepts anything. Validate untrusted data separately.
## Narrowing helpers
- Write user-defined type guards with `TypeIs` (3.13+, narrows in both branches) and use `TypeGuard` only when the narrowed type is not a subtype of the input.
- Use `typing.assert_never(x)` in the final `else`/`case _` of an exhaustive match over a union or enum.
## Other useful features
- `Self` (3.11+) for methods returning their own class. `@override` (3.12+) on methods that override a base class method. `Callable[[int], str]` or a callback `Protocol` for functions.
## Checking
- Run the project's checker in its configured mode, for example `mypy --strict src/` or `pyright` with `"typeCheckingMode": "strict"`. New code should introduce no new errors.
- Do not silence errors with `cast(...)` or `# type: ignore` unless you add a comment explaining why. Prefer `# type: ignore[code]` with the specific error code.
## Verify before finishing
- Type checker passes on changed files. Public functions have complete signatures. No new bare `Any` appears in public APIs.
- Run the tests too. Type hints are not enforced at runtime.
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.