Skip to content

Re-broaden type to Any if it started as Any but was narrowed in an enclosing frame #3361

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 5 commits into from
Jul 11, 2017
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
14 changes: 9 additions & 5 deletions mypy/binder.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,12 +221,16 @@ def assign_type(self, expr: Expression,
# times?
return

# If x is Any and y is int, after x = y we do not infer that x is int.
# This could be changed.

if (isinstance(self.most_recent_enclosing_type(expr, type), AnyType)
enclosing_type = self.most_recent_enclosing_type(expr, type)
if (isinstance(enclosing_type, AnyType)
and not restrict_any):
pass
# If x is Any and y is int, after x = y we do not infer that x is int.
# This could be changed.
if not isinstance(type, AnyType):
# We narrowed type from Any in a recent frame (probably an
# isinstance check), but now it is reassigned, so broaden back
# to Any (which is the most recent enclosing type)
self.put(expr, enclosing_type)
elif (isinstance(type, AnyType)
and not (isinstance(declared_type, UnionType)
and any(isinstance(item, AnyType) for item in declared_type.items))):
Expand Down
14 changes: 14 additions & 0 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -1712,3 +1712,17 @@ if isinstance(x, (set, (list, T))):
reveal_type(x) # E: Revealed type is 'Union[builtins.set[Any], builtins.list[Any], builtins.int, builtins.str]'

[builtins fixtures/isinstancelist.pyi]


[case testIsinstanceNarrowAny]
from typing import Any

def narrow_any_to_str_then_reassign_to_int() -> None:
v = 1 # type: Any

if isinstance(v, str):
reveal_type(v) # E: Revealed type is 'builtins.str'
v = 2
reveal_type(v) # E: Revealed type is 'Any'

[builtins fixtures/isinstance.pyi]