On Tue, May 21, 2013 at 12:35 AM, r.david.murray <python-check...@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 | ncogh...@gmail.com | Brisbane, Australia _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com