Skip to content

Commit

Permalink
typing: allow union types for instance_of
Browse files Browse the repository at this point in the history
fixes #1336
  • Loading branch information
hynek committed Dec 14, 2024
1 parent 103d51f commit 1094ba5
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 0 deletions.
2 changes: 2 additions & 0 deletions changelog.d/1385.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
`attrs.validators.instance_of()`'s type hints now allow for union types.
For example: `instance_of(str | int)`
3 changes: 3 additions & 0 deletions src/attr/validators.pyi
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from types import UnionType
from typing import (
Any,
AnyStr,
Expand Down Expand Up @@ -44,6 +45,8 @@ def instance_of(
) -> _ValidatorType[_T1 | _T2 | _T3]: ...
@overload
def instance_of(type: tuple[type, ...]) -> _ValidatorType[Any]: ...
@overload
def instance_of(type: UnionType) -> _ValidatorType[_T]: ...
def optional(
validator: (
_ValidatorType[_T]
Expand Down
3 changes: 3 additions & 0 deletions tests/typing_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ class Validated:
k: int | str | C = attr.ib(
validator=attrs.validators.instance_of((int, C, str))
)
kk: int | str | C = attr.ib(
validator=attrs.validators.instance_of(int | C | str)
)

l: Any = attr.ib(
validator=attr.validators.not_(attr.validators.in_("abc"))
Expand Down

0 comments on commit 1094ba5

Please sign in to comment.