Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Signal unreachability when narrowing with TypeGuard[Never] or TypeIs[Never] #17830

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5889,9 +5889,15 @@ def find_isinstance_check_helper(
# Also note that a care must be taken to unwrap this back at read places
# where we use this to narrow down declared type.
if node.callee.type_guard is not None:
if isinstance(
get_proper_type(node.callee.type_guard), UninhabitedType
):
return None, {}
return {expr: TypeGuardedType(node.callee.type_guard)}, {}
else:
assert node.callee.type_is is not None
if isinstance(get_proper_type(node.callee.type_is), UninhabitedType):
return None, {}
return conditional_types_to_typemaps(
expr,
*self.conditional_types_with_intersection(
Expand Down
38 changes: 38 additions & 0 deletions test-data/unit/check-unreachable-code.test
Original file line number Diff line number Diff line change
Expand Up @@ -1507,3 +1507,41 @@ x = 0 # not unreachable

f2: Callable[[], NoReturn] = lambda: foo()
x = 0 # not unreachable

[case testUnreachableTypeGuardNever]
# flags: --warn-unreachable
from typing_extensions import Never, TypeGuard

def guard(x: object) -> TypeGuard[Never]:
pass

a: object
assert not guard(a)

if guard(a):
reveal_type(a) # E: Statement is unreachable
else:
reveal_type(a) # N: Revealed type is "builtins.object"

assert guard(a)
b = 0 # E: Statement is unreachable
[builtins fixtures/tuple.pyi]

[case testUnreachableTypeIsNever]
# flags: --warn-unreachable
from typing_extensions import Never, TypeIs

def guard(x: object) -> TypeIs[Never]:
pass

a: object
assert not guard(a)

if guard(a):
reveal_type(a) # E: Statement is unreachable
else:
reveal_type(a) # N: Revealed type is "builtins.object"

assert guard(a)
b = 0 # E: Statement is unreachable
[builtins fixtures/tuple.pyi]
Loading