You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Certain patterns of if isinstance(...) cause mypy to forget that a variable has a particular generic type.
To Reproduce
Run the following Python code through mypy with --strict:
fromtypingimportTypeVar# context:T=TypeVar('T')
classA: passclassB: passdeffunction1(obj: T) ->T: # expected behaviour:ifisinstance(obj, A):
passelifisinstance(obj, B):
passreturnobj# no problem heredeffunction2(obj: T) ->T: # unexpected behaviour:ifisinstance(obj, (A, B)):
passreturnobj# mypy has forgotten that obj is of type T
The issue also reproduces with this alternate definition of function2:
deffunction2(obj: T) ->T: # unexpected behaviour:ifisinstance(obj, A) orisinstance(obj, B):
passreturnobj# mypy has forgotten that obj is of type T
Expected Behavior
mypy should issue no errors.
Actual Behavior
<last line of function2>: error: Returning Any from function declared to return "T"
[no-any-return]
return obj # mypy has forgotten that 'obj' is of type 'T'
^
Found 1 error in 1 file (checked 1 source file)
Your Environment
Mypy version used: mypy 0.910
Mypy command-line flags: --strict
Mypy configuration options from mypy.ini (and other config files): no additional flags are necessary to reproduce the issue
Python version used: CPython 3.8.3 (from pyenv)
Operating system and version: macOS 10.14
The text was updated successfully, but these errors were encountered:
It could very well be the same root cause; given my lack of knowledge of mypy internals, I can't say. If there is a distinction, it's this: in #10817, it appears that the type of the variable is being positively inferred, overriding the already-known generic type. In this issue, no inference is possible, but the type somehow changes from the generic T to Any.
I also note that in this issue, testing against one class (at a time) is not sufficient to trigger the problem; testing against two classes is required. (See function1, which behaves as expected.)
Bug Report
Certain patterns of
if isinstance(...)
cause mypy to forget that a variable has a particular generic type.To Reproduce
Run the following Python code through mypy with
--strict
:The issue also reproduces with this alternate definition of
function2
:Expected Behavior
mypy should issue no errors.
Actual Behavior
Your Environment
--strict
mypy.ini
(and other config files): no additional flags are necessary to reproduce the issueThe text was updated successfully, but these errors were encountered: