Python dot-equals (syntax proposal)

Patrick Maupin pmaupin at gmail.com
Sat May 1 15:22:06 EDT 2010


On May 1, 7:13 am, Tim Chase <t... at thechases.com> 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.
>
>    >>> 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.

Well, I wrote "conceptually" (which I believe is true; it's certainly
true for me) and "sometimes actually" (which I know is true):

>>> x = [1,2,3,4,5]
>>> y = x
>>> x += [6]
>>> y
[1, 2, 3, 4, 5, 6]

>>>
>>> x = set()
>>> y = x
>>> x |= set([1])
>>> y
set([1])

SO, if you find those results "unintuitive", perhaps you should
upgrade your understanding of python.  Personally, I don't find any of
the results I gave, or the results you gave, surprising, so I'm not
saying my "conceptually and sometimes actually modifies the result" is
right for *you* but it works great for me. :-)

> 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).

Well, you should submit a bug report to fix the operation of lists and
sets for a starter.

But first, you might want to read PEP 203 -- augmented assignments.  I
particularly like the section which says:

"The idea behind augmented assignment in Python is that it isn't just
an easier way to write the common practice of storing the result of a
binary operation in its left-hand operand, but also a way for the left-
hand operand in question to know that it should operate `on itself',
rather than creating a modified copy of itself."

There are a lot of sections which have a similar flavor.  If (which I
doubt), the "augmented dot" is accepted, it won't necessarily have the
same meaning.  x = x.foo could replace x with any other kind of
object, and I view it as a replacement, while I view x += foo as a
modification.

Regards,
Pat



More information about the Python-list mailing list