Bug in list comprehensions in Pyhton 2.1.1?

Fernando Pérez fperez528 at yahoo.com
Sat Nov 10 19:44:27 EST 2001


The code below can be copied and run as is. Hopefully it documents
clearly enough what to me seems to be a bug in list comprehensions:
the global namespace is polluted with a local variable which was only
used as the dummy running index of the list comprehension.



If there is a good reason why this behavior is expected, I'd love to
know about it.


Cheers,

f.



# ------------- example code follows

def flatten_bug(seq):
    # a *global* variable x is left over after calling this function,
    # with the  value of the last element in the return list
    return [x for subseq in seq for x in subseq]

def flatten_nobug(seq):
    x = 0  # forces x to be explicitly local. Ugly kludge.
    return [x for subseq in seq for x in subseq]

# test code. Notice a variable x isn't defined anywhere.

lst = [[1,2],[3,4]]

print '\nlist',lst, 'flat_nobug',flatten_nobug(lst)

try:
    print 'x:',x,
    print ' BAD! There should be no global x!'
except:
    print 'x not found. Good, this is as it should be.'
    pass

print '\nlist',lst, 'flat_bug',flatten_bug(lst)

try:
    print 'x:',x,
    print ' BAD! There should be no global x!'
except:
    print 'x not found. Good, this is as it should be.'



More information about the Python-list mailing list