Skip to content

Commit 4a7e5d3

Browse files
authored
Add TypeGuard and TypeIs traversing in TypeTraverserVisitor (#17071)
Fixes #17029.
1 parent 337bcf9 commit 4a7e5d3

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

mypy/typetraverser.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ def visit_callable_type(self, t: CallableType) -> None:
8686
t.ret_type.accept(self)
8787
t.fallback.accept(self)
8888

89+
if t.type_guard is not None:
90+
t.type_guard.accept(self)
91+
92+
if t.type_is is not None:
93+
t.type_is.accept(self)
94+
8995
def visit_tuple_type(self, t: TupleType) -> None:
9096
self.traverse_types(t.items)
9197
t.partial_fallback.accept(self)

test-data/unit/check-typeguard.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,18 @@ def main(a: object, b: object) -> None:
5454
reveal_type(b) # N: Revealed type is "builtins.object"
5555
[builtins fixtures/tuple.pyi]
5656

57+
[case testTypeGuardTypeVarReturn]
58+
from typing import Callable, Optional, TypeVar
59+
from typing_extensions import TypeGuard
60+
T = TypeVar('T')
61+
def is_str(x: object) -> TypeGuard[str]: pass
62+
def main(x: object, type_check_func: Callable[[object], TypeGuard[T]]) -> T:
63+
if not type_check_func(x):
64+
raise Exception()
65+
return x
66+
reveal_type(main("a", is_str)) # N: Revealed type is "builtins.str"
67+
[builtins fixtures/exception.pyi]
68+
5769
[case testTypeGuardIsBool]
5870
from typing_extensions import TypeGuard
5971
def f(a: TypeGuard[int]) -> None: pass

test-data/unit/check-typeis.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,18 @@ def main(a: Tuple[object, ...]):
9292
reveal_type(a) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
9393
[builtins fixtures/tuple.pyi]
9494

95+
[case testTypeIsTypeVarReturn]
96+
from typing import Callable, Optional, TypeVar
97+
from typing_extensions import TypeIs
98+
T = TypeVar('T')
99+
def is_str(x: object) -> TypeIs[str]: pass
100+
def main(x: object, type_check_func: Callable[[object], TypeIs[T]]) -> T:
101+
if not type_check_func(x):
102+
raise Exception()
103+
return x
104+
reveal_type(main("a", is_str)) # N: Revealed type is "builtins.str"
105+
[builtins fixtures/exception.pyi]
106+
95107
[case testTypeIsUnionIn]
96108
from typing import Union
97109
from typing_extensions import TypeIs

0 commit comments

Comments
 (0)