Python dot-equals (syntax proposal)
Peter Otten
__peter__ at web.de
Mon May 3 05:34:19 EDT 2010
Alf P. Steinbach wrote:
> <test lang="py3">
> >>> t = ([], [], [])
> >>> t
> ([], [], [])
> >>> t[0] += ["blah"]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
> >>> t
> (['blah'], [], [])
> >>> _
> </test>
>
> Yep, it matters.
>
> Is this change-but-raise-exception a bug?
No.
a[0] += b
translates to
a.__setitem__(0, a.__getitem__(0).__iadd__(b))
assuming a[0] has an __iadd__() method. It should be obvious that only the
the last operation, the outer a.__setitem__(...), will fail here.
A possible fix might be a changed order of evaluation:
_internal_set = a.__setitem__
_internal_set(0, a.__getitem__(0).__iadd__(b))
I don't know if there are arguments against this other than increased
compiler complexity.
Or one could argue that
a += b
should have been implemented as
a = a + b
or
a = a.__add__(b)
which is currently used as the fallback when there is no __iadd__() method
and which gives a more intuitive behaviour at the cost of a greater
overhead. But it's a little late for that discussion, for that language.
Peter
More information about the Python-list
mailing list