loop scope

Jacek Generowicz jacek.generowicz at cern.ch
Mon Mar 15 04:36:06 EST 2004


"Greg Ewing (using news.cis.dfn.de)" <wmwd2zz02 at sneakemail.com> writes:

> Jacek Generowicz wrote:
> > now simply add list comprehensions (or
> > loops), and you will maintain perfect consistency of treatment of
> > local variables,
> 
> It wouldn't do to make the whole (non-comprehension)
> for-loop a new scope, because that would make any
> variables assigned within the loop body local as well.

Sometimes you want that, and sometimes you don't. What you need is a
way to distinguish between the two. IOW, you want to distinguish
between creating a new binding, and rebinding. In Python both of these
are spelt thus: "=", and its actual meaning is determied by the
context. With the added spice of the exceptional case of "global".

Imagine (for the sake of brevity of argument --- I wouldn't dream of
suggesting such a "line-noise" syntax for Python) that you could use
"x := 3" to mean "create a new local binding for x", while "x = 3"
would mean "find the innermost x and rebind it", with function
parameters, loop variables, list comprehension variables all behaving
as if they were using ":=". Now you'll find that you gain a lot of
flexibility to do what is appropriate with scopes of variables used in
loops etc., and you have an opportunity to fix the immutability of
closures ...

(Of course there are "issues" ... what happens, for
example when you say

    def foo(a):
        a := 3
        a := 4

... does that make three nested scopes for a?, is it an error?)



More information about the Python-list mailing list