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
dict comprehension shouldn't raise UnboundLocalError #75309
Comments
The code Intuitively, the element 'key' and the list 'key' are not the same, so generally the expected result is {"a": 1, "b": 2}. There are similar cases for listcomps, setcomps and genexprs: For consistency and intuitiveness, the behavior of distcomps should be modified so that no UnboundLocalError is raised. |
The behavior is consistent: >>> a = [1, 2]
>>> b = [3, 4]
>>> [(a, b) for a in a for b in b]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
UnboundLocalError: local variable 'b' referenced before assignment I'm not sure why it is only the nested loop that raises the error (https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries seems to imply it should raise for both) By the way, the actual result of your comprehesion would be {"a": 2, "b" 2}. |
Comprehensions evaluate the iterator for the outermost loop in the surrounding scope. The iterators for all inner loops are evaluated in the local scope of the comprehension itself. |
I wonder if that explanation should be added to the doc section to which I pointed. I thought I'd remembered something like that being in there, but it isn't. |
It's consistent with the behavior of generator expressions:
|
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: