Syntactic sugar for assignment statements: one value to multiple targets?

MRAB python at mrabarnett.plus.com
Wed Aug 17 18:55:51 CEST 2011


On 17/08/2011 10:26, gc wrote:
> On Aug 17, 3:13 am, Chris Angelico<ros... at gmail.com>  wrote:
>
>> Minor clarification: You don't want to initialize them to the same
>> value, which you can do already:
>>
>> a=b=c=d=e=dict()
>
> Right. Call the proposed syntax the "instantiate separately for each
> target" operator.  (It can be precisely defined as a * on the RHS of a
> one-into-many assignment statement--i.e. an assignment statement with
> 1 object on the RHS and more than 1 on the LHS).
>
I think that lazy unpacking is the more important issue because we can
replace instantiation with copying:

def copies(obj, count=None):
     if count is None:
         while True:
             yield obj.copy()
     else:
         for i in range(count):
             yield obj.copy()

(Should it yield deep copies, or should there be a separate deep_copies
function?)

> It has only one very modest function, which is to unpack
>
> a, b, c, d, e = *dict()
>
> to
>
> a, b, c, d, e = dict(), dict(), dict(), dict(), dict()
>
This becomes:

a, b, c, d, e = copies(dict(), 5)

With lazy unpacking it would become:

a, b, c, d, e = lazy copies(dict())

(Or whatever the syntax is.)

> so that you have n separate objects instead of one. If you want the
> same object duplicated five times, you'd best use a=b=c=d=e=dict().
> (I'd guess that 90% of the people who try the a=b=c version actually
> *want* separate objects and are surprised at what they get--I made
> that mistake a few times!--but changing either behavior would be a
> very bad idea. This proposed syntax would be the Right Way to get
> separate objects.)
>
> Maybe this is more visibly convenient with a complex class, like
>
> x, y, z = *SuperComplexClass(param1, param2, kwparam = "3", ...)
>
x, y, z = lazy copies(SuperComplexClass(param1, etc, ...))

[snip]



More information about the Python-list mailing list