Skip to content

Commit 677a6fc

Browse files
lincolnqddfisher
authored andcommitted
Re-broaden type to Any if it started as Any but was narrowed in an enclosing frame (#3361)
Fixes #3338.
1 parent 783aaff commit 677a6fc

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

mypy/binder.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -233,12 +233,16 @@ def assign_type(self, expr: Expression,
233233
# times?
234234
return
235235

236-
# If x is Any and y is int, after x = y we do not infer that x is int.
237-
# This could be changed.
238-
239-
if (isinstance(self.most_recent_enclosing_type(expr, type), AnyType)
236+
enclosing_type = self.most_recent_enclosing_type(expr, type)
237+
if (isinstance(enclosing_type, AnyType)
240238
and not restrict_any):
241-
pass
239+
# If x is Any and y is int, after x = y we do not infer that x is int.
240+
# This could be changed.
241+
if not isinstance(type, AnyType):
242+
# We narrowed type from Any in a recent frame (probably an
243+
# isinstance check), but now it is reassigned, so broaden back
244+
# to Any (which is the most recent enclosing type)
245+
self.put(expr, enclosing_type)
242246
elif (isinstance(type, AnyType)
243247
and not (isinstance(declared_type, UnionType)
244248
and any(isinstance(item, AnyType) for item in declared_type.items))):

test-data/unit/check-isinstance.test

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,3 +1754,17 @@ if isinstance(x, str, 1): # E: Too many arguments for "isinstance"
17541754
x = 1
17551755
reveal_type(x) # E: Revealed type is 'builtins.int'
17561756
[builtins fixtures/isinstancelist.pyi]
1757+
1758+
1759+
[case testIsinstanceNarrowAny]
1760+
from typing import Any
1761+
1762+
def narrow_any_to_str_then_reassign_to_int() -> None:
1763+
v = 1 # type: Any
1764+
1765+
if isinstance(v, str):
1766+
reveal_type(v) # E: Revealed type is 'builtins.str'
1767+
v = 2
1768+
reveal_type(v) # E: Revealed type is 'Any'
1769+
1770+
[builtins fixtures/isinstance.pyi]

0 commit comments

Comments
 (0)