Augmented Assignment in Python (PER)

Thomas Wouters thomas at xs4all.net
Wed Jul 18 06:01:12 EDT 2001


On Tue, Jul 17, 2001 at 08:11:51PM -0500, David Beazley wrote:

> I think the above sentence would make a lot more sense if it was
> worded as follows:

> "For the built-in types, augmented assignment doesn't violate
> mutability or perform in-place modification of objects. Therefore,
> writing x+=y creates an entirely new object x with the value x + y.
> User defined types and classes may choose to implement different
> behavior by redefining special methods such as __iadd__(), __isub__(), 
> and so forth."

> Note: I still stand by the statement for built-in types.  I looked through
> the Python sources when writing the book and couldn't find any use of
> augmented assignment for built-in types.  I am not aware of any
> counter-example where x += y is not equal to x = x + y for the standard
> built-in types (if there is such an example, please enlighten me!).

Sure:

>>> x = [1,2]
>>> y = x
>>> id(x), id(y)
(134572540, 134572540)
>>> x += [1,2]
>>> x
[1, 2, 1, 2]
>>> y
[1, 2, 1, 2]
>>> id(x),id(y)
(134572540, 134572540)

Basically, all mutable builtin types that define (the C equivalent of)
'__add__' also define (the C equivalent of) '__iadd__' to work in-place.
Unfortunately (for the learning curve) that means 'just lists' :P

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list