Generator Comprehensions

Skip Montanaro skip at pobox.com
Tue Jan 29 15:36:10 CET 2002


    >> It has always bothered me that the temporary variables inside list
    >> comprehensions are still visible afterwards (and overwrite existing
    >> variables):

    Jason> Wow.  I wasn't aware of that.  But now that I am, it bothers me.

I don't see any spurious locals:

    >>> def f(n):
    ...   l = [i for i in range(n)]
    ...   print locals()
    ...   return l
    ... 
    >>> f(5)
    {'i': 4, 'l': [0, 1, 2, 3, 4], 'n': 5}
    [0, 1, 2, 3, 4]

When you disassemble the function you see a strange local named "_[1]":

    >>> dis.dis(f)
              0 SET_LINENO               1

              3 SET_LINENO               2
              6 BUILD_LIST               0
              9 DUP_TOP             
             10 LOAD_ATTR                0 (append)
             13 STORE_FAST               1 (_[1])
             16 LOAD_GLOBAL              2 (range)
             19 LOAD_FAST                0 (n)
             22 CALL_FUNCTION            1
             25 GET_ITER            

        >>   26 SET_LINENO               2
             29 FOR_ITER                16 (to 48)
             32 STORE_FAST               2 (i)
             35 LOAD_FAST                1 (_[1])
             38 LOAD_FAST                2 (i)
             41 CALL_FUNCTION            1
             44 POP_TOP             
             45 JUMP_ABSOLUTE           26
        >>   48 DELETE_FAST              1 (_[1])
             51 STORE_FAST               3 (l)

             54 SET_LINENO               3
             57 LOAD_GLOBAL              6 (locals)
             60 CALL_FUNCTION            0
             63 PRINT_ITEM          
             64 PRINT_NEWLINE       

             65 SET_LINENO               4
             68 LOAD_FAST                3 (l)
             71 RETURN_VALUE        
             72 LOAD_CONST               0 (None)
             75 RETURN_VALUE        

but you can't access it.  Nesting list comprehensions just increments the
number in the brackets.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list