From 4a7e5d3aa4e434e45746365a24638ecfd8b42b50 Mon Sep 17 00:00:00 2001 From: Evgeniy Slobodkin Date: Fri, 29 Mar 2024 03:38:28 +0300 Subject: [PATCH] Add TypeGuard and TypeIs traversing in TypeTraverserVisitor (#17071) Fixes #17029. --- mypy/typetraverser.py | 6 ++++++ test-data/unit/check-typeguard.test | 12 ++++++++++++ test-data/unit/check-typeis.test | 12 ++++++++++++ 3 files changed, 30 insertions(+) diff --git a/mypy/typetraverser.py b/mypy/typetraverser.py index 1ff5f6685eb8..a28bbf422b61 100644 --- a/mypy/typetraverser.py +++ b/mypy/typetraverser.py @@ -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) diff --git a/test-data/unit/check-typeguard.test b/test-data/unit/check-typeguard.test index 66c21bf3abe1..27b88553fb43 100644 --- a/test-data/unit/check-typeguard.test +++ b/test-data/unit/check-typeguard.test @@ -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 diff --git a/test-data/unit/check-typeis.test b/test-data/unit/check-typeis.test index 04b64a45c8c1..6b96845504ab 100644 --- a/test-data/unit/check-typeis.test +++ b/test-data/unit/check-typeis.test @@ -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