Python dot-equals (syntax proposal)
Alf P. Steinbach
alfps at start.no
Sat May 1 10:45:51 EDT 2010
On 01.05.2010 14:13, * Tim Chase:
> 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.
>
> >>> from decimal import Decimal
> >>> d = Decimal(42)
> >>> e = Decimal(18)
> >>> orig = d
> >>> d += e
> >>> d
> Decimal("60")
> >>> e
> Decimal("18")
> >>> orig
> Decimal("42")
> >>> d is orig
> False
>
> If your suggestion that += *modifies* the object, then orig would now
> unintuitively contain 60 and "d is orig" would return True.
In some cases += modifies the object. For CPython this is an optimization for
the 'str' type, reducing to O(n) time the common newbie O(n^2) loops. The
criterion for doing it is that there is exactly 1 reference (as is the case
after a first append, subsequent appends can just modify).
> This doesn't preclude you from implementing a self-mutating += style
> __add__ method and returning "self", but it's usually a bad idea unless
> it's dire for performance (and even then, think it over a couple times).
Agreed, at the Python level one doesn't in general have the necessary
information to do it safely. Nothwithstanding the current CPython and Jython
documentation error of sys.getrefcount (or whatever the name was) that indicates
that it's available in any implementation.
Cheers,
- Alf
More information about the Python-list
mailing list