Augmented Assignement (was: Re: PEP scepticism)

Alex Martelli aleaxit at yahoo.com
Sat Jun 30 09:47:36 EDT 2001


"Marcin 'Qrczak' Kowalczyk" <qrczak at knm.org.pl> wrote in message
news:slrn.pl.9jrfp7.4in.qrczak at qrnik.zagroda...
> Fri, 29 Jun 2001 20:39:48 +0400 (MSD), Roman Suzi <rnd at onego.ru> pisze:
>
> > In fact, many things depend on the type of the objects. Types of the
> > objects define what operation will be done. For example, in a simple
> >
> > A = A + 1
> >
> > + operation is different for different A type.
>
> But it never modifies A,

"Never?  Well, *hardly* ever" (music by Lord Sullivan, of course).

class sic:
    def __init__(self):
        self.chip = 0
    def __add__(self, other):
        self.chip += 1
        return 23

A=sic()
B=A
print B.chip
A = A + 1
print A
print B.chip

> and always returns an object which has a
> type similar to the type of A (not necessarily exactly, numeric types

See above for "always".

> I treat as a wart the fact that augmented assignment has a subtle
> difference between mutable and immutable objects.

I do not consider polymorphism a wart, not even when it lets
you write horrid code as in "class sic" above.

> Both flavors of appending make sense in isolation. But in 2/3 of cases
> the programmer must be aware which flavor is used. Using a wrong

Where do you get this datum?!  A fast browse of all occurrences
of += in the .py files of the standard library appears to confirm my
intuition that by far MOST cases of += fall into what you claim is
"1/3" of the cases:

> The remaining 1/3 is where it doesn't matter which variant is chosen:
> where the old reference would be discarded anyway, so indeed +=
> sometimes gives the best implementation for the given type.

_By far most often_.  It's the exceptional case where you += to an
object that has more than one reference, and the other reference(s)
are not just "still around", but actually likely to be used for something
later, after the +=.


Alex






More information about the Python-list mailing list