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

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:: + + >>> atuple = (1, 2) + >>> atuple[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 atuple[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 = atuple[0].iadd(1) + >>> atuple[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 = atuple[0] + 1 atuple[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