8000 Retain None (unreachable) when typemap is None with `type(x) is Foo` … · python/mypy@b82697b · GitHub
[go: up one dir, main page]

Skip to content

Commit b82697b

Browse files
authored
Retain None (unreachable) when typemap is None with type(x) is Foo check (#18486)
Fixes #18428. Prevents rewriting `None` ("unreachable") typemaps as empty dicts ("nothing to infer")
1 parent 42b5999 commit b82697b

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

mypy/checker.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6021,6 +6021,8 @@ def is_type_call(expr: CallExpr) -> bool:
60216021

60226022
def combine_maps(list_maps: list[TypeMap]) -> TypeMap:
60236023
"""Combine all typemaps in list_maps into one typemap"""
6024+
if all(m is None for m in list_maps):
6025+
return None
60246026
result_map = {}
60256027
for d in list_maps:
60266028
if d is not None:

test-data/unit/check-isinstance.test

Lines changed: 27 additions & 0 deletions
Diff line number
Original file line numberDiff line change
@@ -2660,6 +2660,33 @@ y: Any
26602660
if type(y) is int:
26612661
reveal_type(y) # N: Revealed type is "builtins.int"
26622662

2663+
[case testTypeEqualsCheckUsingIsNonOverlapping]
2664+
# flags: --warn-unreachable
2665+
from typing import Union
2666+
2667+
y: str
2668+
if type(y) is int: # E: Subclass of "str" and "int" cannot exist: would have incompatible method signatures
2669+
y # E: Statement is unreachable
2670+
else:
2671+
reveal_type(y) # N: Revealed type is "builtins.str"
2672+
[builtins fixtures/isinstance.pyi]
2673+
2674+
[case testTypeEqualsCheckUsingIsNonOverlappingChild-xfail]
2675+
# flags: --warn-unreachable
2676+
from typing import Union
2677+
2678+
class A: ...
2679+
class B: ...
2680+
class C(A): ...
2681+
x: Union[B, C]
2682+
# C instance cannot be exactly its parent A, we need reversed subtyping relationship
2683+
# here (type(parent) is Child).
2684+
if type(x) is A:
2685+
reveal_type(x) # E: Statement is unreachable
2686+
else:
2687+
reveal_type(x) # N: Revealed type is "Union[__main__.B, __main__.C]"
2688+
[builtins fixtures/isinstance.pyi]
2689+
26632690
[case testTypeEqualsNarrowingUnionWithElse]
26642691
from typing import Union
26652692

test-data/unit/check-typevar-values.test

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,3 +732,16 @@ def foo3(x: NT) -> None:
732732
def foo4(x: NT) -> None:
733733
p, q = 1, 2.0 # type: (int, float)
734734
[builtins fixtures/tuple.pyi]
735+
736+
[case testTypeVarValuesNarrowing]
737+
from typing import TypeVar
738+
739+
W = TypeVar("W", int, str)
740+
741+
def fn(w: W) -> W:
742+
if type(w) is str:
743+
reveal_type(w) # N: Revealed type is "builtins.str"
744+
elif type(w) is int:
745+
reveal_type(w) # N: Revealed type is "builtins.int"
746+
return w
747+
[builtins fixtures/isinstance.pyi]

0 commit comments

Comments
 (0)
0