-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Incorrect inference with isinstance() #2993
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Yes, the way type objects are represented right now is kind of messy. Until we clean up the implementation, mypy should support all the possible representations of type objects in all contexts. The second case would be a reasonable thing to fix if the fix is simple enough, though clearly it's not a high priority thing. Could you actually create a separate issue for the second case, since it seems like an independent issue? |
Actually, I was wrong: the 1) issue has nothing to do with whether And yes, I can separate them out. |
Ah yeah, I didn't read the first example correctly. Yes, if one the types is a
|
I'm moving item 2) into a separate issue as you suggested. |
What's the issue# for the separate issue you created for (2)? Also does #2997 fix this or (2) or both? |
I think there are a few problems with
isinstance
inference.mypy --strcit --python-version 3.6
, but it should not:The semantic analyzer concludes that within the body of
if isinstance()
, the type ofx
must beint
. It's not, however. For example, in this casef('a', str)
, theif
branch will be followed even thoughx
is not anint
(and this will cause runtimeTypeError
without any mypy warnings).The reason this happens is that
type
annotation is represented as anInstance
rather than as aFunctionLike
insidechecker.py:get_isinstance_type()
. As a result, it's skipped entirely in the loop, and onlyint
is added totypes
, so sem analyzer thinksx
must absolutely beint
.One solution is to make
type
represented with an instance ofCallableType
(why isn't it btw?!). Another solution is to simply add a bit of logic to the loop to properly handle this case.results in
error: Argument 2 to "isinstance" has incompatible type "Tuple[str, Tuple[List[_T], Tuple[_T_co, ...]]]"; expected "Union[type, Tuple[type, ...]]"
.This is because there's this weird thing in python that allows to put nested tuples as the second argument to
isinstance
, andmypy
(along with most other people) doesn't know about it. I don't know if it's worth fixing, but it's super easy (just flatten the second argument if it's a tuple).If my understanding is correct, I'll make a PR.
The text was updated successfully, but these errors were encountered: