Skip to content

Commit bfc78a0

Browse files
committed
avoid narrowing type(x) to type(y: Any)
1 parent 9a1459d commit bfc78a0

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

mypy/checker.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6782,6 +6782,13 @@ def narrow_type_by_identity_equality(
67826782
expr = operands[j]
67836783

67846784
current_type_range = self.get_isinstance_type(expr)
6785+
if current_type_range is not None:
6786+
target_type = get_proper_type(
6787+
make_simplified_union([tr.item for tr in current_type_range])
6788+
)
6789+
if isinstance(target_type, AnyType):
6790+
# Avoid widening to Any for checks like `type(x) is type(y: Any)`.
6791+
continue
67856792
if_map, else_map = conditional_types_to_typemaps(
67866793
expr_in_type_expr,
67876794
*self.conditional_types_with_intersection(

test-data/unit/check-narrowing.test

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3068,6 +3068,16 @@ if type(x) == type(y) == int:
30683068
reveal_type(y) # N: Revealed type is "builtins.int"
30693069
reveal_type(x) # N: Revealed type is "builtins.int"
30703070

3071+
[case testTypeEqualsCheckDoesNotWidenToAny]
3072+
# flags: --strict-equality --warn-unreachable
3073+
from typing import Any
3074+
3075+
x: str
3076+
y: Any
3077+
if type(y) is type(x):
3078+
reveal_type(x) # N: Revealed type is "builtins.str"
3079+
reveal_type(y) # N: Revealed type is "builtins.str"
3080+
30713081
[case testTypeEqualsCheckUsingIs]
30723082
# flags: --strict-equality --warn-unreachable
30733083
from typing import Any

0 commit comments

Comments
 (0)