a = b = 1 just syntactic sugar?
Ed Avis
ed at membled.com
Thu Jun 5 13:57:36 EDT 2003
Michael Chermside <mcherm at mcherm.com> writes:
>> 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 =.
> table = {'setcolour': lambda setgs, x: setattr(setgs, 'b', x),
> 'invertcolour': lambda setgs, x: setattr(setgs, 'b', inverted[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.
Yes. Or even, instead of having a new class each time it might be
worthwhile to define a 'holder':
class Holder(object):
def set(v):
self.v = v
def get():
return self.v
bh = Holder()
table = {'setcolour': lambda x: bh.set(x), ...}
So inside the parallel universe of lambda expressions, a.set(b) is
what you say instead of a = b.
It seems a bit perverse that setattr is allowed in lambda expressions
but assignment is not; that you can call setdefault to update a
dictionary, but not simply set the dictionary's elements; that you can
do sys.stdout.write but not print; that you can call a function which
asserts but not call assert.
If lambda accepted statements as well as expressions - or if a
statement could be used as an expression, as in C - then these warts
would not arise.
--
Ed Avis <ed at membled.com>
More information about the Python-list
mailing list