Augmented Assignement (was: Re: PEP scepticism)

Bernhard Herzog bh at intevation.de
Fri Jun 29 09:39:04 EDT 2001


"Steve Holden" <sholden at holdenweb.com> writes:

> "Bernhard Herzog" <bh at intevation.de> wrote in message
> news:6qn16r7i69.fsf at abnoba.intevation.de...
> > Carsten Geckeler <uioziaremwpl at spammotel.com> writes:
> >
> > > As mentioned above, for tuples the "+=" is completely natural, but not
> for
> > > lists.
> >
> > Funny, I mostly see it exactly the other way round. += modifies the left
> > hand side in place, so it's natural for a list, but not for a tuple.
> >
> I suppose that depends. Given the following initialization code:
> 
>     lst = [1, 2, 3]
>     tpl = (1, 2, 3)
>     lstx = lst
>     tplx = tpl
> 
> would you expect the same results from
> 
>     lst += ["extra"]
>     tpl += ("extra", )

Well, this could modify lst and/or tpl in place ...

> 
> and
> 
>     lst = lst + ["extra"]
>     tpl = tpl + ("extra", )

... while this usually creates new objects and doesn't modify either lst
or tpl (unless they implement __add__ in an unsual way).

> to be the same?

So, I wouldn't expect them to behave in the same way.

OTOH, consider the statement

    x += (1,2,3)

Does that modify x in place? This works regardless of whether x is a
tuple or a list, but if x is a list x is modified in place while if it's
a tuple it isn't. (interestingly enough x += [1,2,3] gives a TypeError
if x is a tuple.)

One consequence for me is that I'll very careful with augmented
assignments. It seems to me the only situation in which their use should
be considered is when it's OK to modify the object on the LHS in place
(which is basically what the pep says, too).

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                               http://mapit.de/



More information about the Python-list mailing list