Skip to content

Disable promotions in isinstance checks #6114

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

Merged
Merged
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
5 changes: 3 additions & 2 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3756,11 +3756,12 @@ def conditional_type_map(expr: Expression,
proposed_type = UnionType([type_range.item for type_range in proposed_type_ranges])
if current_type:
if (not any(type_range.is_upper_bound for type_range in proposed_type_ranges)
and is_proper_subtype(current_type, proposed_type)):
and is_proper_subtype(current_type, proposed_type, ignore_promotions=True)):
# Expression is always of one of the types in proposed_type_ranges
return {}, None
elif not is_overlapping_types(current_type, proposed_type,
prohibit_none_typevar_overlap=True):
prohibit_none_typevar_overlap=True,
ignore_promotions=True):
# Expression is never of any type in proposed_type_ranges
return None, {}
else:
Expand Down
17 changes: 17 additions & 0 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -1313,6 +1313,23 @@ def f(x: Union[A, B]) -> None:
f(x)
[builtins fixtures/isinstance.pyi]

[case testIsinstanceWithOverlappingPromotionTypes]
from typing import Union

class FloatLike: pass
class IntLike(FloatLike): pass

def f1(x: Union[float, int]) -> None:
# We ignore promotions in isinstance checks
if isinstance(x, float):
reveal_type(x) # E: Revealed type is 'builtins.float'

def f2(x: Union[FloatLike, IntLike]) -> None:
# ...but not regular subtyping relationships
if isinstance(x, FloatLike):
reveal_type(x) # E: Revealed type is 'Union[__main__.FloatLike, __main__.IntLike]'
[builtins fixtures/isinstance.pyi]

[case testIsinstanceOfSuperclass]
class A: pass
class B(A): pass
Expand Down