a = b = 1 just syntactic sugar?

Bengt Richter bokr at oz.net
Tue Jun 10 11:15:20 CEST 2003


On 05 Jun 2003 18:57:36 +0100, Ed Avis <ed at membled.com> wrote:

>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.
>
You can use = fairly freely if you redefine that class and parenthesize
your "assignments," e.g.,

 >>> class NS:
 ...     def __init__(self, **kw): self.__dict__.update(kw)
 ...     __call__ = __init__
 ...
 >>> ns = NS(x=123)
 >>> ns.x
 123
 >>> ns(x=0, y=456)
 >>> ns.x, ns.y
 (0, 456)
 >>> ns(x=2,y=3) or ns(z=ns.x*ns.y) or ns.z
 6
 >>> vars(ns)
 {'y': 3, 'x': 2, 'z': 6}
 >>> import sys
 >>> w=sys.stdout.write
 >>> ns(x=0) or w(str(ns.x)) or ns(x=' new!') or w(ns.x+'\n')
 0 new!

 ... just to be perverse using expressions ;-)

>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.
There are long threads in the past discussing how to deal with indenting though.
I thought it could be done, but it was pretty unusual not to have a clean way
of using a preceding def instead and referring to it.

Regards,
Bengt Richter




More information about the Python-list mailing list