Python dot-equals (syntax proposal)

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat May 1 21:32:34 EDT 2010


On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote:

> On 05/01/2010 12:08 AM, Patrick Maupin wrote:
>> +=, -=, /=, *=, etc.  conceptually (and, if lhs object supports in-
>> place operator methods, actually) *modify* the lhs object.
>>
>> Your proposed .= syntax conceptually *replaces* the lhs object
>> (actually, rebinds the lhs symbol to the new object).
> 
> The += family of operators really do rebind the symbol, not modify the
> object.

They potentially do both, depending on the object, even for built-ins.


>    >>> from decimal import Decimal
[...]

I'm not sure why you took the trouble to import Decimal for this example, 
when you could have shown the same thing with built-ins int or float. All 
three types are immutable.

A counter example with a mutable type:

>>> a = []
>>> b = a
>>> a += [2]
>>> a
[2]
>>> b
[2]

thus demonstrating that __iadd__ modifies in place as well as rebinds for 
at least one mutable type.

> This doesn't preclude you from implementing a self-mutating += style
> __add__ method and returning "self", but it's usually a bad idea 

Obviously the Python dev team don't agree with that :)

Just to prove that += for lists is not an accident:

>>> a = set()
>>> b = a
>>> a |= set([1])
>>> a
set([1])
>>> b
set([1])



-- 
Steven



More information about the Python-list mailing list