Skip to content

Disable promotions when restricting types in isinstance checks #6142

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 1 commit into from
Jan 4, 2019
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
3 changes: 2 additions & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3764,7 +3764,8 @@ def conditional_type_map(expr: Expression,
proposed_precise_type = UnionType([type_range.item
for type_range in proposed_type_ranges
if not type_range.is_upper_bound])
remaining_type = restrict_subtype_away(current_type, proposed_precise_type)
remaining_type = restrict_subtype_away(current_type, proposed_precise_type,
ignore_promotions=True)
return {expr: proposed_type}, {expr: remaining_type}
else:
return {expr: proposed_type}, {}
Expand Down
8 changes: 5 additions & 3 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -997,7 +997,7 @@ def unify_generic_callable(type: CallableType, target: CallableType,
return applied


def restrict_subtype_away(t: Type, s: Type) -> Type:
def restrict_subtype_away(t: Type, s: Type, *, ignore_promotions: bool = False) -> Type:
"""Return t minus s.

If we can't determine a precise result, return a supertype of the
Expand All @@ -1014,8 +1014,10 @@ def restrict_subtype_away(t: Type, s: Type) -> Type:
# TODO: Implement more robust support for runtime isinstance() checks,
# see issue #3827
new_items = [item for item in t.relevant_items()
if (not (is_proper_subtype(erase_type(item), erased_s) or
is_proper_subtype(item, erased_s))
if (not (is_proper_subtype(erase_type(item), erased_s,
ignore_promotions=ignore_promotions) or
is_proper_subtype(item, erased_s,
ignore_promotions=ignore_promotions))
or isinstance(item, AnyType))]
return UnionType.make_union(new_items)
else:
Expand Down
2 changes: 2 additions & 0 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -1323,6 +1323,8 @@ 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'
else:
reveal_type(x) # E: Revealed type is 'builtins.int'

def f2(x: Union[FloatLike, IntLike]) -> None:
# ...but not regular subtyping relationships
Expand Down