inconsistency with += between different types ?

Delaney, Timothy tdelaney at avaya.com
Thu Aug 8 01:53:17 CEST 2002


> From: Andreas.Leitgeb at siemens.at [mailto:Andreas.Leitgeb at siemens.at]
> 
> That's exactly what I meant.
> For immutable objects, __iadd__ et al. simply make no sense (IMHO).
> 
> To Christopher and other defendants of status quo:
>  Do you know of any real use that a not-self-mutating __ixxx__ 
>  may have, which its non-i version __xxx__ could not do ?

Performance.

Using augmented assignment, a lookup is performed for __iadd__. If that
fails (an AttributeException thrown) then __add__ is looked up. Lookups and
thrown exceptions are expensive.

Immutable objects may well choose to implement __iadd__ for the performance
boost. In that case, the code is usually:

class I:

    def __add__(self, other):
        ...
        return self

    __radd__ = __iadd__
    __iadd__ = __add__

Tim Delaney




More information about the Python-list mailing list