Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > List comprehension/genexp inconsistency.

Reply
Thread Tools

List comprehension/genexp inconsistency.

 
 
J. Cliff Dyer
Guest
Posts: n/a
 
      03-20-2012
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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Java Collections List : Converting from List '<Column <String1,String2>>' to 'List <String1>' asil klin Java 28 03-05-2011 01:59 AM
Memory issues when storing as List of Strings vs List of List OW Ghim Siong Python 2 11-30-2010 12:22 PM
Appending a list's elements to another list using a list comprehension Debajit Adhikary Python 17 10-18-2007 06:45 PM
Why does list.__getitem__ return a list instance for subclasses ofthe list type? dackz Python 0 02-06-2007 04:44 PM
Difference Between List x; and List x(); , if 'List' is a Class? roopa C++ 6 08-27-2004 06:18 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57