Skip to content

Commit 0bbf714

Browse files
miedzinskiilevkivskyi
authored andcommitted
Widen type to Any when isinstance(..., Any) is True (#3751)
Fixes #3474
1 parent cdbc7db commit 0bbf714

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

mypy/checker.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3233,6 +3233,8 @@ def get_isinstance_type(expr: Expression,
32333233
elif isinstance(typ, Instance) and typ.type.fullname() == 'builtins.type':
32343234
object_type = Instance(typ.type.mro[-1], [])
32353235
types.append(TypeRange(object_type, is_upper_bound=True))
3236+
elif isinstance(typ, AnyType):
3237+
types.append(TypeRange(typ, is_upper_bound=False))
32363238
else: # we didn't see an actual type, but rather a variable whose value is unknown to us
32373239
return None
32383240
if not types:

test-data/unit/check-isinstance.test

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1975,3 +1975,33 @@ def f() -> None:
19751975
[typing fixtures/typing-full.pyi]
19761976
[builtins fixtures/dict.pyi]
19771977
[out]
1978+
1979+
[case testIsinstanceWidensWithAnyArg]
1980+
from typing import Any
1981+
class A: ...
1982+
B: Any
1983+
x: A
1984+
x.foo() # E: "A" has no attribute "foo"
1985+
assert isinstance(x, B)
1986+
x.foo()
1987+
reveal_type(x) # E: Revealed type is 'Any'
1988+
[builtins fixtures/isinstance.pyi]
1989+
1990+
[case testIsinstanceWidensUnionWithAnyArg]
1991+
from typing import Any, Union
1992+
class A: ...
1993+
B: Any
1994+
x: Union[A, B]
1995+
reveal_type(x) # E: Revealed type is 'Union[__main__.A, Any]'
1996+
assert isinstance(x, B)
1997+
reveal_type(x) # E: Revealed type is 'Any'
1998+
[builtins fixtures/isinstance.pyi]
1999+
2000+
[case testIsinstanceIgnoredImport]
2001+
from typing import Union
2002+
from foo import A # type: ignore
2003+
def f(x: Union[A, str]) -> None:
2004+
x.method_only_in_a() # E: Item "str" of "Union[Any, str]" has no attribute "method_only_in_a"
2005+
if isinstance(x, A):
2006+
x.method_only_in_a()
2007+
[builtins fixtures/isinstance.pyi]

0 commit comments

Comments
 (0)