Skip to content

Commit be952b9

Browse files
committed
Try respecting explicit Any annotation
1 parent efaaa90 commit be952b9

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

mypy/binder.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,13 @@ def assign_type(self, expr: Expression, type: Type, declared_type: Type | None)
370370
else:
371371
# In all other cases we don't narrow to Any to minimize false negatives.
372372
self.put(expr, declared_type)
373+
elif isinstance(p_declared, AnyType):
374+
# Mirroring the first case above, we don't narrow to a precise type if the variable
375+
# has an explicit `Any` type annotation.
376+
if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred:
377+
self.put(expr, type)
378+
else:
379+
self.put(expr, declared_type)
373380
else:
374381
self.put(expr, type)
375382

test-data/unit/check-dynamic-typing.test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ if int():
252252
if int():
253253
a = d.foo(a, a)
254254
d.x = a
255-
d.x.y.z # E: "A" has no attribute "y"
255+
d.x.y.z
256256

257257
class A: pass
258258
[out]

test-data/unit/check-isinstance.test

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1915,12 +1915,24 @@ if isinstance(x, str, 1): # E: Too many arguments for "isinstance"
19151915
reveal_type(x) # N: Revealed type is "builtins.int"
19161916
[builtins fixtures/isinstancelist.pyi]
19171917

1918-
[case testIsinstanceNarrowAny]
1918+
[case testIsinstanceNarrowAnyExplicit]
19191919
from typing import Any
19201920

19211921
def narrow_any_to_str_then_reassign_to_int() -> None:
19221922
v: Any = 1
19231923

1924+
if isinstance(v, str):
1925+
reveal_type(v) # N: Revealed type is "builtins.str"
1926+
v = 2
1927+
reveal_type(v) # N: Revealed type is "Any"
1928+
[builtins fixtures/isinstance.pyi]
1929+
1930+
[case testIsinstanceNarrowAnyImplicit]
1931+
def foo(): ...
1932+
1933+
def narrow_any_to_str_then_reassign_to_int() -> None:
1934+
v = foo()
1935+
19241936
if isinstance(v, str):
19251937
reveal_type(v) # N: Revealed type is "builtins.str"
19261938
v = 2

0 commit comments

Comments
 (0)