a = b = 1 just syntactic sugar?

Michael Chermside mcherm at mcherm.com
Thu Jun 5 08:31:32 EDT 2003


Ed Avis writes:
> Lambda expressions are restricted to contain expressions, not
> statements.  This makes it difficult to write table-driven code such
> as
> 
>     commands = [...]
>     inverted = {'red': 'cyan', ...}
>     b = 'blue' # default
>     table = {'setcolour': lambda x: b = x,
>              'invertcolour': lambda x: b = inverted[b],
>              ...,
>             }
>     for (c, arg) in commands:
>       table[c](arg)
>     print 'after reading config file, colour is', b
> 
> This code with the 'table' dictionary can be more maintainable than a
> big long if/elif/elif statement, although that is not always the case.
> 
> However it is not possible to write it as above because anonymous
> functions don't allow assignment, or at least, not with =.

Well, there are of course other ways to do it (as others have pointed
out) but if you like your table of anonymous functions, it's certainly
still usable. The problem is that you are trying to store the
settings, like 'b', as local (or global?) variables. Its much better
to have an object. Something like this:

    class Settings:
        def __init__(self):
            self.b = 'blue' # default
            self.otherStuff = 'otherDefault' # etc
    g_settings = Settings()


    commands = [...]
    inverted = {'red': 'cyan', ...}
    table = {'setcolour': lambda setgs, x: setattr(setgs, 'b', x),
             'invertcolour': lambda setgs, x: setattr(setgs, 'b', inverted[b]),
             ...,
            }
    for (c, arg) in commands:
      table[c](g_settings, arg)
    print 'after reading config file, colour is', g_settings.b

Of course, you can argue that using setattr is simply another way of
doing assignment (but with a function, so it can be done in a lamda) --
which would be true. And you can suggest that it'd be cleaner if
Settings had a setDefaultColor() method which you called -- true again.

Somehow, migrating from using a bunch of variables to using an object
just makes things easier. Obviously, it's not the only approach, but
if you like your tables of anonymous functions, this is a way to do it.

-- Michael Chermside






More information about the Python-list mailing list