-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
isinstance checks cause type declarations to leak from the binder #1568
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
There's a Python 2 vs. 3 issue here too: in Python 2, the original 'x'
value leaks out into the outer scope; in Python 3, it doesn't.
|
Right. But I think I'd be pretty reasonable to tell people not to use that in Python 2. |
Hi @ecprice :) |
#1044 looks like it might be the same issue. |
I think the top commit of my typebinder branch fixes this. It probably cleanly applies to master, but I haven't checked. |
I'm actually not going to fix this right now, in part because the correct behavior isn't entirely clear; should we treat comprehension loop variables as deleted after the comprehension (maybe only in Python 2 mode)? |
In CPython, comprehension variables are deleted only in Python 3. But I'm
fine with mypy treating them as deleted everywhere -- even in Python 2
mode. If you reference a leaked comprehension variable your code is very
smelly. Another aspect of comprehensions is that we should not insist on
the same variable having the same type throughout a function.
Also note that generator expressions are different -- the are always their
own scope even in Python 2.
|
Oh right and there's also the tricky bit that while list comprehensions are evaluated immediately (of course), only the first sequence in a generator comprehension is evaluated immediately. So technically we should not use information from the binder for any sequence expression past the first. (Like we don't use information from the binder when checking the body of a lambda, since the variables it refers to may have changed value by the time the lambda is executed.) |
The output now is |
I am not sure how this got fixed, but the current behaviour looks right to me. |
The problem with this is most easily visible with list comprehensions:
This happens because of this line in the binder, which always adds the declared type of a variable to the topmost frame whenever a binding for it is pushed: https://github.com/python/mypy/blob/master/mypy/checker.py#L127
This is obviously a bug, but it's not yet clear what the best way to fix the issue is. The binder is small, but complicated -- perhaps the best fix is it rewrite it in a more understandable/robust way?
This issue is the reason mypy still has a self-typecheck error with #1562.
The text was updated successfully, but these errors were encountered: