Augmented Assignement (was: Re: PEP scepticism)

Bruce Sass bsass at freenet.edmonton.ab.ca
Fri Jun 29 15:42:44 EDT 2001


On 29 Jun 2001, Bernhard Herzog wrote:
> "Steve Holden" <sholden at holdenweb.com> writes:
> > 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?

yes

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

It would be nice if this was "fixed"... lists and tuples should behave
the same (well, except for that mutability thing).  It doesn't bother
me at all that implicit mutability mutating would be going on, the
ability to use tuples as "locked" versions of lists sounds too
appealing.

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

How about _if_ lists and tuples differed only in their mutability;
concatenating, extending, appending, slices and indexing would become
ways to lock and unlock subsets of the sequence.

I don't do enough programming to know just how useful this would be,
the symmetry is nice but maybe it would be too much work for too
little gain.


- Bruce





More information about the Python-list mailing list