Skip to content

Commit

Permalink
Widen type to Any when isinstance(..., Any) is True (#3751)
Browse files Browse the repository at this point in the history
Fixes #3474
  • Loading branch information
miedzinski authored and ilevkivskyi committed Nov 22, 2017
1 parent cdbc7db commit 0bbf714
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions mypy/checker.py
Expand Up @@ -3233,6 +3233,8 @@ def get_isinstance_type(expr: Expression,
elif isinstance(typ, Instance) and typ.type.fullname() == 'builtins.type':
object_type = Instance(typ.type.mro[-1], [])
types.append(TypeRange(object_type, is_upper_bound=True))
elif isinstance(typ, AnyType):
types.append(TypeRange(typ, is_upper_bound=False))
else: # we didn't see an actual type, but rather a variable whose value is unknown to us
return None
if not types:
Expand Down
30 changes: 30 additions & 0 deletions test-data/unit/check-isinstance.test
Expand Up @@ -1975,3 +1975,33 @@ def f() -> None:
[typing fixtures/typing-full.pyi]
[builtins fixtures/dict.pyi]
[out]

[case testIsinstanceWidensWithAnyArg]
from typing import Any
class A: ...
B: Any
x: A
x.foo() # E: "A" has no attribute "foo"
assert isinstance(x, B)
x.foo()
reveal_type(x) # E: Revealed type is 'Any'
[builtins fixtures/isinstance.pyi]

[case testIsinstanceWidensUnionWithAnyArg]
from typing import Any, Union
class A: ...
B: Any
x: Union[A, B]
reveal_type(x) # E: Revealed type is 'Union[__main__.A, Any]'
assert isinstance(x, B)
reveal_type(x) # E: Revealed type is 'Any'
[builtins fixtures/isinstance.pyi]

[case testIsinstanceIgnoredImport]
from typing import Union
from foo import A # type: ignore
def f(x: Union[A, str]) -> None:
x.method_only_in_a() # E: Item "str" of "Union[Any, str]" has no attribute "method_only_in_a"
if isinstance(x, A):
x.method_only_in_a()
[builtins fixtures/isinstance.pyi]

0 comments on commit 0bbf714

Please sign in to comment.