Skip to content

Commit 51e34fa

Browse files
authored
Disable promotions in isinstance checks (#6114)
This pull request resolves #6060 by modifying `conditional_type_map` function in `checker.py` to ignore promotions.
1 parent baef333 commit 51e34fa

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

mypy/checker.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3756,11 +3756,12 @@ def conditional_type_map(expr: Expression,
37563756
proposed_type = UnionType([type_range.item for type_range in proposed_type_ranges])
37573757
if current_type:
37583758
if (not any(type_range.is_upper_bound for type_range in proposed_type_ranges)
3759-
and is_proper_subtype(current_type, proposed_type)):
3759+
and is_proper_subtype(current_type, proposed_type, ignore_promotions=True)):
37603760
# Expression is always of one of the types in proposed_type_ranges
37613761
return {}, None
37623762
elif not is_overlapping_types(current_type, proposed_type,
3763-
prohibit_none_typevar_overlap=True):
3763+
prohibit_none_typevar_overlap=True,
3764+
ignore_promotions=True):
37643765
# Expression is never of any type in proposed_type_ranges
37653766
return None, {}
37663767
else:

test-data/unit/check-isinstance.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,6 +1313,23 @@ def f(x: Union[A, B]) -> None:
13131313
f(x)
13141314
[builtins fixtures/isinstance.pyi]
13151315

1316+
[case testIsinstanceWithOverlappingPromotionTypes]
1317+
from typing import Union
1318+
1319+
class FloatLike: pass
1320+
class IntLike(FloatLike): pass
1321+
1322+
def f1(x: Union[float, int]) -> None:
1323+
# We ignore promotions in isinstance checks
1324+
if isinstance(x, float):
1325+
reveal_type(x) # E: Revealed type is 'builtins.float'
1326+
1327+
def f2(x: Union[FloatLike, IntLike]) -> None:
1328+
# ...but not regular subtyping relationships
1329+
if isinstance(x, FloatLike):
1330+
reveal_type(x) # E: Revealed type is 'Union[__main__.FloatLike, __main__.IntLike]'
1331+
[builtins fixtures/isinstance.pyi]
1332+
13161333
[case testIsinstanceOfSuperclass]
13171334
class A: pass
13181335
class B(A): pass

0 commit comments

Comments
 (0)