Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #21947 > unrolled thread
| Started by | "J. Cliff Dyer" <jcd@sdf.lonestar.org> |
|---|---|
| First post | 2012-03-20 16:23 -0400 |
| Last post | 2012-03-20 16:23 -0400 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
List comprehension/genexp inconsistency. "J. Cliff Dyer" <jcd@sdf.lonestar.org> - 2012-03-20 16:23 -0400
| From | "J. Cliff Dyer" <jcd@sdf.lonestar.org> |
|---|---|
| Date | 2012-03-20 16:23 -0400 |
| Subject | List comprehension/genexp inconsistency. |
| Message-ID | <mailman.841.1332275170.3037.python-list@python.org> |
One of my coworkers just stumbled across an interesting issue. I'm hoping someone here can explain why it's happening. When trying to create a class with a dual-loop generator expression in a class definition, there is a strange scoping issue where the inner variable is not found, (but the outer loop variable is found), while a list comprehension has no problem finding both variables. Demonstration: >>> class Spam: ... foo, bar = 4, 4 ... baz = dict(((x, y), x+y) for x in range(foo) for y in range(bar)) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in Spam File "<stdin>", line 3, in <genexpr> NameError: global name 'bar' is not defined >>> class Eggs(object): ... foo, bar = 4, 4 ... baz = dict([((x, y), x+y) for x in range(foo) for y in range(bar)]) ... >>> This was discovered in python 2.6. In python 3.2, both versions fail with the same NameError. Obviously, this is easy enough to work around. I'm curious though: What's going on under the hood to cause the nested generator expression to fail while the list comprehension succeeds? Cheers, Cliff
Back to top | Article view | comp.lang.python
csiph-web