[Tutor] inconsistent destruction

eryksun eryksun at gmail.com
Thu Aug 8 08:15:32 CEST 2013


On Wed, Aug 7, 2013 at 11:54 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> This bugs me for some reason. The final variable is saved in a for
> loop but not in a list comprehension. It just seems to me they should
> both be destroyed to avoid confusion.

FYI, in 2.x a comprehension executes in the current scope, i.e. it
leaks. A 3.x comprehension uses a function:

    >>> code = compile('[cnt for cnt in range(5)]', '', 'eval')

The main code instantiates the function and iterator, and then calls
the function:

    >>> dis.dis(code)
     0 LOAD_CONST               0 (<code object <listcomp>)
     3 LOAD_CONST               1 ('<listcomp>')
     6 MAKE_FUNCTION            0
     9 LOAD_NAME                0 (range)
    12 LOAD_CONST               2 (5)
    15 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
    18 GET_ITER
    19 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
    22 RETURN_VALUE

The 0th constant is the compiled code for the comprehension:

    >>> dis.dis(code.co_consts[0])
     0 BUILD_LIST               0
     3 LOAD_FAST                0 (.0)
     6 FOR_ITER                12 (to 21)
     9 STORE_FAST               1 (cnt)
    12 LOAD_FAST                1 (cnt)
    15 LIST_APPEND              2
    18 JUMP_ABSOLUTE            6
    21 RETURN_VALUE

> lst = []
> for cnt in range(5):
>     lst.append(cnt)
> cnt
> 4
>
> Is there a form of for loop that would destroy the loop variable? I
> could always do del cnt right after the for, but that seems
> artificial.

There are tricks you can do manually with exec() and decorators, but
nothing simple enough to be worth considering. Just use a function;
the loop will even perform a bit better with "cnt" as a fast local
instead of a dict key.

Nick Coghlan has given the problem a lot of thought in two competing
PEPs (both deferred):

Statement local namespaces (aka "given" clause)
http://www.python.org/dev/peps/pep-3150

General purpose decorator clause (aka "@in" clause)
http://www.python.org/dev/peps/pep-0403


More information about the Tutor mailing list