[Python-Dev] 2.5 and beyond

Tim Peters tim.peters at gmail.com
Sun Jul 2 03:08:25 CEST 2006


[Tim]
>> Don't recall what that was, but creating a new scope on each iteration
>> sounds hard to explain in Python.

[Andrew Koenig]
> I don't think it's particularly hard to explain.  For example, one way to explain it is
> to say that
>
>         for i in <<stuff>>:
>                 body
>
> is equivalent to
>
>         for <<hiddenvar>> in <<stuff>>:
>                 local i = <<hiddenvar>>
>                 body
>
> This explanation doesn't need to rest on recursion.

Sorry, but as a Python programmer that explanation makes little sense
to me.  In effect, it pushes the mystery into what "local" is supposed
to mean, but there's nothing _already_ in Python that acts the way you
need "local" to act.

Scope in Python is defined wrt "blocks", so you need to phrase this in
terms of blocks, and there are very few kinds of blocks in Python's
execution model:

    A block is a piece of Python program text that is executed as a unit.
    The following are blocks: a module, a function body, and a class definition.
    Each command typed interactively is a block. A script file (a file given as
    standard input to the interpreter or specified on the interpreter command
    line the first argument) is a code block. A script command (a command
    specified on the interpreter command line with the `-c' option) is a code
    block. The file read by the built-in function execfile() is a code block.
    The string argument passed to the built-in function eval() and to the exec
    statement is a code block. The expression read and evaluated by the
    built-in function input() is a code block.

That's from section "Naming and binding" of the Python Reference
Manual.  I expect most Python programmers have "module, function,
class ... plus some weird stuff I don't much care about" in mind.
Python's execution model also has a one-to-one correspondence between
active blocks and execution frames (see the rest of that section),
which would need to be snapped to consider a finer-grained notion of
block that didn't have its own execution frame.

In short, it's only easy to define this in Python, without invoking
nested functions, if you don't have Python's execution model in mind
to begin with.


More information about the Python-Dev mailing list