Skip to content

Commit ca6ce8c

Browse files
laydayhynekpre-commit-ci[bot]
authored
Use TypeGuard for has in Python 3.10 and above (#997)
* Use `TypeGuard` for `has` in Python 3.10 and above * fixup! Use `TypeGuard` for `has` in Python 3.10 and above * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Test the negative case * Add type guard example Co-authored-by: Hynek Schlawack <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 006b31f commit ca6ce8c

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

src/attr/__init__.pyi

+6-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ from . import validators as validators
2727
from ._cmp import cmp_using as cmp_using
2828
from ._version_info import VersionInfo
2929

30+
if sys.version_info >= (3, 10):
31+
from typing import TypeGuard
32+
else:
33+
from typing_extensions import TypeGuard
34+
3035
__version__: str
3136
__version_info__: VersionInfo
3237
__title__: str
@@ -470,7 +475,7 @@ def astuple(
470475
tuple_factory: Type[Sequence[Any]] = ...,
471476
retain_collection_types: bool = ...,
472477
) -> Tuple[Any, ...]: ...
473-
def has(cls: type) -> bool: ...
478+
def has(cls: type) -> TypeGuard[Type[AttrsInstance]]: ...
474479
def assoc(inst: _T, **changes: Any) -> _T: ...
475480
def evolve(inst: _T, **changes: Any) -> _T: ...
476481

tests/test_mypy.yml

+12
Original file line numberDiff line numberDiff line change
@@ -1371,3 +1371,15 @@
13711371
b: str
13721372
13731373
fields(A) # E: Argument 1 to "fields" has incompatible type "Type[A]"; expected "Type[AttrsInstance]"
1374+
1375+
- case: testHasTypeGuard
1376+
main: |
1377+
from attrs import define, has
1378+
1379+
@define
1380+
class A:
1381+
pass
1382+
1383+
reveal_type(A) # N: Revealed type is "def () -> main.A"
1384+
if has(A):
1385+
reveal_type(A) # N: Revealed type is "Type[attr.AttrsInstance]"

tests/typing_example.py

+6
Original file line numberDiff line numberDiff line change
@@ -416,3 +416,9 @@ def accessing_from_attrs() -> None:
416416
attrs.setters.frozen
417417
attrs.validators.and_
418418
attrs.cmp_using
419+
420+
421+
def has_typeguard() -> None:
422+
foo = object
423+
if attrs.has(foo):
424+
foo.__attrs_attrs__

0 commit comments

Comments
 (0)