loop scope

Dan Bishop danb_83 at yahoo.com
Thu Mar 18 16:24:51 EST 2004


Jacek Generowicz <jacek.generowicz at cern.ch> wrote in message news:<tyfd67e4fll.fsf at pcepsft001.cern.ch>...
[snip]
> 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?)

One way to avoid this problem is to have an explicit scope-creating
construct instead.

def foo(a):
   scope outer:
      a = 3
      scope inner:
         a = 4
         print a            # prints 4
         print outer.a      # prints 3
         print foo.a        # prints the function parameter
      print a               # inner.a is out of scope, so prints 3
      foo.b = 5             # Creates a new function-scope variable.
   print b                  # prints 5



More information about the Python-list mailing list