[Python-Dev] [Python-checkins] cpython (3.3): #17973: Add FAQ entry for ([], )[0] += [1] both extending and raising.

Nick Coghlan ncoghlan at gmail.com
Tue May 21 15:24:17 CEST 2013


On Tue, May 21, 2013 at 12:35 AM, r.david.murray
<python-checkins at python.org> wrote:
Yay for having this in the FAQ, but...
> +If you wrote::
> +
> + >>> a_tuple = (1, 2)
> + >>> a_tuple[0] += 1
> + Traceback (most recent call last):
> + ...
> + TypeError: 'tuple' object does not support item assignment
> +
> +The reason for the exception should be immediately clear: ``1`` is added to the
> +object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
> +but when we attempt to assign the result of the computation, ``2``, to element
> +``0`` of the tuple, we get an error because we can't change what an element of
> +a tuple points to.
> +
> +Under the covers, what this augmented assignment statement is doing is
> +approximately this::
> +
> + >>> result = a_tuple[0].__iadd__(1)
> + >>> a_tuple[0] = result
> + Traceback (most recent call last):
> + ...
> + TypeError: 'tuple' object does not support item assignment

For the immutable case, this expansion is incorrect:
>>> hasattr(0, "__iadd__")
False
With immutable objects, += almost always expands to:
>>> result = a_tuple[0] + 1
>>> a_tuple[0] = result

(For containers that support binary operators, the presence of the
relevant __i*__ methods is actually a reasonable heuristic for
distinguishing the mutable and immutable versions)
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /