a = b = 1 just syntactic sugar?

Steven Taschuk staschuk at telusplanet.net
Wed Jun 4 16:58:00 EDT 2003


Quoth Ed Avis:
  [...]
>     table = {'setcolour': lambda x: b = x,
>              'invertcolour': lambda x: b = inverted[b],
>              ...,
>             }
  [...]
> However it is not possible to write it as above because anonymous
> functions don't allow assignment, or at least, not with =.

And there'd be scope problems anyway.

How about this instead?

    class config(object):
        def __init__(self):
            self.colour = 'blue'
        def setcolour(self, value):
            self.colour = value
        def invertcolour(self, dummy):
            self.colour = inverted[self.colour]
        # ...

    cfg = config()
    for cmd, arg in commands:
        getattr(cfg, cmd)(arg)
    print 'colour is now', cfg.colour

Some refinements are in order (e.g., to prevent the configuration
file from invoking __init__), but the idea is clear.  This
technique does assume that the command names fit into identifier
syntax, of course.

-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list