List comprehension/genexp inconsistency.

J

J. Cliff Dyer

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:
.... 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
.... 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top