Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1666.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Documented how to type custom validator functions using `attrs.Attribute` on Python versions before 3.14.
48 changes: 48 additions & 0 deletions docs/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,54 @@ As of Python 3.14, this is no longer necessary because it introduced [*deferred
In both cases, if you need to resolve these to real types, you can call {func}`attrs.resolve_types`, which will update the attributes in place.


## Typing validators

When typing custom validator functions, you may want to annotate the *attribute* parameter as `attrs.Attribute[int]` or `attrs.Attribute[T]`.
Because {class}`attrs.Attribute` is declared generic in the type stubs (`.pyi`) rather than at runtime, subscripting it directly in an eagerly evaluated annotation raises `TypeError` on Python versions before 3.14.

To avoid that runtime error while keeping strict static typing, either defer annotation evaluation with `from __future__ import annotations` (or Python 3.14+ deferred annotations), or quote the annotation as a string literal:

```python
from __future__ import annotations

from typing import Any

import attrs


def positive(
instance: Any, attribute: attrs.Attribute[int], value: int
) -> None:
if value <= 0:
raise ValueError(f"{attribute.name} must be positive")


@attrs.define
class Item:
count: int = attrs.field(validator=positive)
```

Without `from __future__ import annotations` on Python 3.13 and earlier, quote the subscripted type instead:

```python
from typing import Any

import attrs


def positive(
instance: Any, attribute: "attrs.Attribute[int]", value: int
) -> None:
if value <= 0:
raise ValueError(f"{attribute.name} must be positive")


@attrs.define
class Item:
count: int = attrs.field(validator=positive)
```


## Class variables and constants

Defining an attribute with a type annotation and assigned value looks like a class variable, but it isn't.
Expand Down