[Python-Dev] PEP for Better Control of Nested Lexical Scopes (original) (raw)

Mark Russell mrussell at verio.net
Tue Feb 21 21:41:26 CET 2006


On 21 Feb 2006, at 19:25, Jeremy Hylton wrote:

If I recall the discussion correctly, Guido said he was open to a version of nested scopes that allowed rebinding.

PEP 227 mentions using := as a rebinding operator, but rejects the
idea as it would encourage the use of closures. But to me it seems
more elegant than some special keyword, especially is it could also
replace the "global" keyword. It doesn't handle things like "x += y"
but I think you could deal with that by just writing "x := x + y".

BTW I do think there are some cases where replacing a closure with a
class is not an improvement. For example (and assuming the existence
of :=):

 def check_items(items):
     had_error = False

     def err(mesg):
         print mesg
         had_error := True

     for item in items:
         if too_big(item):
             err("Too big")
         if too_small(item):
             err("Too small")

     if had_error:
         print "Some items were out of range"

Using a class for this kind of trivial bookkeeping just adds
boilerplate and obscures the main purpose of the code:

 def check_items(items):
     class NoteErrors (object):
         def __init__(self):
             self.had_error = False

         def __call__(self, mesg):
             print mesg
             self.had_error = True

     err = NoteErrors()

     for item in items:
         if too_big(item):
             err("Too big")
         if too_small(item):
             err("Too small")

     if err.had_error:
         print "Some items were out of range"

Any chance of := (and removing "global") in python 3K?

Mark Russell



More information about the Python-Dev mailing list