a = b = 1 just syntactic sugar?

Ed Avis ed at membled.com
Wed Jun 4 21:43:50 CEST 2003


sismex01 at hebmex.com writes:

>>Is there a way to write an expression which sets b and does return
>>something?
> 
>I really don't know, but the real question is: why?
>What are you trying to accomplish?

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 =.

(I've also had a similar problem with putting 'assert' inside lambda
expressions, which seems like a reasonable thing to do if you want to
write an anonymous function which requires that its argument be a
positive number, for example.  In the end I wrote my own 'my_assert'
function which asserts the given expression and returns it.  There is
a kind of parallel universe that you must inhabit when writing
anonymous functions.)

>Programming "C/C++ in Python" is frustrating,

Rest assured, I am not trying to do that :-P.

-- 
Ed Avis <ed at membled.com>




More information about the Python-list mailing list