Skip to content

Commit

Permalink
Add TypeGuard and TypeIs traversing in TypeTraverserVisitor (#17071)
Browse files Browse the repository at this point in the history
Fixes #17029.
  • Loading branch information
sloboegen committed Mar 29, 2024
1 parent 337bcf9 commit 4a7e5d3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions mypy/typetraverser.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ def visit_callable_type(self, t: CallableType) -> None:
t.ret_type.accept(self)
t.fallback.accept(self)

if t.type_guard is not None:
t.type_guard.accept(self)

if t.type_is is not None:
t.type_is.accept(self)

def visit_tuple_type(self, t: TupleType) -> None:
self.traverse_types(t.items)
t.partial_fallback.accept(self)
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-typeguard.test
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ def main(a: object, b: object) -> None:
reveal_type(b) # N: Revealed type is "builtins.object"
[builtins fixtures/tuple.pyi]

[case testTypeGuardTypeVarReturn]
from typing import Callable, Optional, TypeVar
from typing_extensions import TypeGuard
T = TypeVar('T')
def is_str(x: object) -> TypeGuard[str]: pass
def main(x: object, type_check_func: Callable[[object], TypeGuard[T]]) -> T:
if not type_check_func(x):
raise Exception()
return x
reveal_type(main("a", is_str)) # N: Revealed type is "builtins.str"
[builtins fixtures/exception.pyi]

[case testTypeGuardIsBool]
from typing_extensions import TypeGuard
def f(a: TypeGuard[int]) -> None: pass
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-typeis.test
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ def main(a: Tuple[object, ...]):
reveal_type(a) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
[builtins fixtures/tuple.pyi]

[case testTypeIsTypeVarReturn]
from typing import Callable, Optional, TypeVar
from typing_extensions import TypeIs
T = TypeVar('T')
def is_str(x: object) -> TypeIs[str]: pass
def main(x: object, type_check_func: Callable[[object], TypeIs[T]]) -> T:
if not type_check_func(x):
raise Exception()
return x
reveal_type(main("a", is_str)) # N: Revealed type is "builtins.str"
[builtins fixtures/exception.pyi]

[case testTypeIsUnionIn]
from typing import Union
from typing_extensions import TypeIs
Expand Down

0 comments on commit 4a7e5d3

Please sign in to comment.