Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #21947
| Subject | List comprehension/genexp inconsistency. |
|---|---|
| From | "J. Cliff Dyer" <jcd@sdf.lonestar.org> |
| Date | 2012-03-20 16:23 -0400 |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.841.1332275170.3037.python-list@python.org> (permalink) |
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 comp.lang.python | Previous | Next | Find similar | Unroll thread
List comprehension/genexp inconsistency. "J. Cliff Dyer" <jcd@sdf.lonestar.org> - 2012-03-20 16:23 -0400
csiph-web