This confuses every Python developer the first time they see it—even if they're pretty experienced by the time they see it:
    >>> t = ([], [])
    >>> t[0] += [1]
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <stdin> in <module>()
    ----> 1 t[0] += [1]
    
    TypeError: 'tuple' object does not support item assignment
So far, so good. But now:
    >>> t
    ([1], [])
So the addition succeeded, but also failed!

This is discussed in the official FAQ, but most people don't read that FAQ—and those who do seem to immediately start trying to think of "solutions" without fully understanding the underlying issue. So let's dig into it at a lower level.

How assignment works

Let's take a simpler case first:
    >>> t = [0, 1]
    >>> t[0] = 2
    >>> t
    [2, 1]
In many languages, like C++, what happens here is that t[0] doesn't return 0, but some kind of reference object, which acts like the original 0 in most contexts, but if you modify it—including by assignment—the first element of t sees the change. Like this:
    >>> _x = getitem(t, 0)
    >>> _x.__assign__(2)
But Python doesn't do this. There is no object that's like 0 except when you modify it; there's just 0, which you can't modify. Assignment doesn't modify an object, it just makes the left side into a new name for the value on the right side. And in fact, t[0] isn't even an expression in this context; it's a special thing called an assignment target.

So what actually happens is:
    >>> x = setitem(t, 0, 2)
This avoids some pretty hairy stuff that comes up in languages like C++. If you want to design, say, a tree-based sorted list contained in C++, the __getitem__ has to return a really smart reference-like object (and you have to design and implement those smarts) that knows how to handle __assign__ by changing the value and then moving it to the right new location in the tree to maintain the sorting. And then you have to think about what happens with references to references. (Imagine a sorted list of references to the values in a dictionary.) Also, because you may not want to create this heavy-weight reference object every time someone just wants to see a value, you have to deal with constness—you overload __getitem__ to return a plain value in const contexts, and a fancy reference value otherwise. And so on (and let's not even get into rvalue vs. lvalue references…).

None of that comes up in Python: __getitem__ just returns a plain-old value (an int, in this case), and all the tree-rebalancing just happens in __setitem__.

Of course this means that Python has a whole parallel grammar for assignment targets that's similar to, but not identical to (a subset of) the grammar for expressions. But it's not all that complicated. A target can be:
  • a simple identifier, in which case you're creating or replacing a local, closure, or global variable of that name.
  • an attribution (something ending with ".foo"), in which case you're calling setattr on the thing to the left of the last "." (which _is_ effectively an expression, although with slightly restricted syntax—it has to be a "primary expression").
  • a subscription or slicing (something ending with [1] or [:3]), in which case you're calling setitem on the thing to the left of the last "[", with the value or slice inside the brackets as an argument.
  • a target list (one or more targets separated by commas, like "x, y[0]", optionally inside parens or square brackets—which looks a lot like a tuple or list display expresson), in which case you're doing iterable unpacking, verifying that there are exactly 2 elements, and assigning the first value to the first target and the second to the second.
This is still a bit oversimplified (it doesn't handle extended iterable unpacking with "*spam", chained assignments like "x = y, z = 2, 3", etc.); see the language reference for full details. But it's all pretty intuitive once you get the idea. (By the way, anyone who wants to propose further extensions to assignment targets really needs to understand how the existing system works. The fact that Joshua Landau does is a big part of the reason PEP 448 is under serious consideration, while most such proposals die out after a half-dozen posts on python-ideas…)

How augmented assignment works

Now let's look at this case:
    >>> t = [0, 1]
    >>> t[0] += 2
    >>> t
    [2, 1]
In a C++ style language, this just means reference objects have to have an __iadd__ method that affects the original value, just like their __assign__ method. But Python doesn't have __assign__, so how does it handle this?

Well, for this case, Python could just treat it the same as t[0] = t[0] + 2, like this:
    >>> setitem(t, 0, getitem(t, 0) + 2)
That works fine for immutable objects, but it doesn't work right for mutable objects like lists. For example:
    >>> x = [0]
    >>> t = [x, [1]]
    >>> t[0] += [2]
    >>> t
    [[0, 2], [1]]
    >>> x
    [0, 2]
Here, t[0] refers to the same object as x. You don't just replace it with a different object, you modify the object in-place. To handle this, Python has an __iadd__ method, similar to __add__, but making the change in-place. (In fact, for a list, __iadd__ is the same thing as extend.) So for this case, Python could just treat it the same as t[0].__iadd__([2]). But that wouldn't work for immutable objects like integers.

So, what Python does is both. Since we don't have except expressions (at least not yet), I'll have to fake it with a series of separate statements:
    
    >>> _tmp = getitem(t, 0)
    >>> try:
    >>>     _tmp2 = _tmp.__iadd__([2])
    >>> except AttributeError:
    >>>     _tmp2 = _tmp.__add__([2])
    >>> setitem(t, 0, _tmp2)

Back to the original example

    >>> t = ([], [])
    >>> t[0] += [1]
So, that += first calls getitem(t, 0). So far, so good. Then it calls __iadd__ on the resulting list. Since that's a list, that's fine; the list is extended in-place, and returns self. Then it calls setitem(t, 0, <the modified list>). Since t is a tuple, that raises an exception. But t[0] has already been modified in-place. Hence the confusing result.

Could we fix this somehow?

It's not clear how. Python can't know that setitem is going to raise an exception until it actually calls it. And it can't call it until it has the value to pass. And it doesn't have that value until it calls __iadd__. At which point the list has been modified.

You might argue that Python could know that setitem will raise, by testing hasattr(t, '__setitem__') and skipping the rest of the statement, synthesizing an AttributeError instead. But let's look at a similar case where that can't possibly work:
    >>> f = open('foo')
    >>> f.encoding += '16'
    AttributeError: readonly attribute
The exact same thing is going on here, but with setattr rather than setitem failing. (Fortunately, because a file's encoding is a string, which is immutable, we're not modifying it and then failing, but it's easy to construct an example with a read-only mutable attribute.)

And here, there's no way to predict in advance that it's going to fail. The problem isn't that __setattr__ doesn't exist, but that it raises an exception when called specifically with 'encoding'. If you call it with some different attribute, it'll work fine. What's happened is that io.TextIOWrapper is a C extension type that's declared 'encoding' as a readonly attribute—or, if you're using the pure-Python implementation, _pyio.TextIOWrapper is a Python class that's declared 'encoding' as a @property with no setter. There are plenty of other ways to make __setattr__ fail, and Python can't check them all in advance.

One option that _might_ work would be to add some new methods to the data model, __cansetitem__(i) and __cansetattr__(name), which does nothing if __setitem__(i, value) would work for some value, but raises if __setitem__(i) would raise. Then, Python could do this:
    
    >>> _tmp = getitem(t, 0)
    >>> cansetitem(t, 0)
    >>> try:
    >>>     _tmp2 = _tmp.__iadd__([2])
    >>> except AttributeError:
    >>>     _tmp2 = _tmp.__add__([2])
    >>> setitem(t, 0, _tmp2)
The __cansetitem__ method would be pretty simple, and could be added to existing collection types; you could even make MutableSequence.__cansetitem__ just call __getitem__ and ignore the result and MutableMapping.__cansetitem__ always return successfully and that'll make most third-party ABC-mixing-derived types just work.

The __cansetattr__ method would be a bit more complicated, however. A base implementation in object.__cansetattr__ can fail for readonly attributes of C extension types, for read-only descriptors (to handle @property and custom descriptors), and for non-declared attributes of C extension types and __slots__ types. But every class with a custom __setattr__ would need a custom __cansetattr__. And there are a lot of those out there, so this would be a backward-compatibility nightmare.

Maybe someone can think of a way around this, or come up with a different solution. If you think you've got one, post it to the python-ideas list. But remember that, as Guido says, language design is not just solving puzzles. The fact that __setitem__ and __setattr__ are resolved dynamically is a feature, and a lot of things (including the "no need for reference types" raised above) flow naturally from that feature. And the surprising behavior of "t[0] += [2]" also flows naturally from that feature. So, there's a good chance any "solution" to the problem will actually be unnatural and more surprising under the covers. And solving a problem with deep magic that's harder to understand than the original problem is usually not a good idea.
11

View comments

Hybrid Programming
Hybrid Programming
5
Greenlets vs. explicit coroutines
Greenlets vs. explicit coroutines
6
ABCs: What are they good for?
ABCs: What are they good for?
1
A standard assembly format for Python bytecode
A standard assembly format for Python bytecode
6
Unified call syntax
Unified call syntax
8
Why heapq isn't a type
Why heapq isn't a type
1
Unpacked Bytecode
Unpacked Bytecode
3
Everything is dynamic
Everything is dynamic
1
Wordcode
Wordcode
1
For-each loops should define a new variable
For-each loops should define a new variable
4
Views instead of iterators
Views instead of iterators
2
How lookup _could_ work
How lookup _could_ work
2
How lookup works
How lookup works
7
How functions work
How functions work
2
Why you can't have exact decimal math
Why you can't have exact decimal math
2
Can you customize method resolution order?
Can you customize method resolution order?
1
Prototype inheritance is inheritance
Prototype inheritance is inheritance
1
Pattern matching again
Pattern matching again
The best collections library design?
The best collections library design?
1
Leaks into the Enclosing Scope
Leaks into the Enclosing Scope
2
Iterable Terminology
Iterable Terminology
8
Creating a new sequence type is easy
Creating a new sequence type is easy
2
Going faster with NumPy
Going faster with NumPy
2
Why isn't asyncio too slow?
Why isn't asyncio too slow?
Hacking Python without hacking Python
Hacking Python without hacking Python
1
How to detect a valid integer literal
How to detect a valid integer literal
2
Operator sectioning for Python
Operator sectioning for Python
1
If you don't like exceptions, you don't like Python
If you don't like exceptions, you don't like Python
2
Spam, spam, spam, gouda, spam, and tulips
Spam, spam, spam, gouda, spam, and tulips
And now for something completely stupid…
And now for something completely stupid…
How not to overuse lambda
How not to overuse lambda
1
Why following idioms matters
Why following idioms matters
1
Cloning generators
Cloning generators
5
What belongs in the stdlib?
What belongs in the stdlib?
3
Augmented Assignments (a += b)
Augmented Assignments (a += b)
11
Statements and Expressions
Statements and Expressions
3
An Abbreviated Table of binary64 Values
An Abbreviated Table of binary64 Values
1
IEEE Floats and Python
IEEE Floats and Python
Subtyping and Ducks
Subtyping and Ducks
1
Greenlets, threads, and processes
Greenlets, threads, and processes
6
Why don't you want getters and setters?
Why don't you want getters and setters?
8
The (Updated) Truth About Unicode in Python
The (Updated) Truth About Unicode in Python
1
How do I make a recursive function iterative?
How do I make a recursive function iterative?
1
Sockets and multiprocessing
Sockets and multiprocessing
Micro-optimization and Python
Micro-optimization and Python
3
Why does my 100MB file take 1GB of memory?
Why does my 100MB file take 1GB of memory?
1
How to edit a file in-place
How to edit a file in-place
ADTs for Python
ADTs for Python
5
A pattern-matching case statement for Python
A pattern-matching case statement for Python
2
How strongly typed is Python?
How strongly typed is Python?
How do comprehensions work?
How do comprehensions work?
1
Reverse dictionary lookup and more, on beyond z
Reverse dictionary lookup and more, on beyond z
2
How to handle exceptions
How to handle exceptions
2
Three ways to read files
Three ways to read files
2
Lazy Python lists
Lazy Python lists
2
Lazy cons lists
Lazy cons lists
1
Lazy tuple unpacking
Lazy tuple unpacking
3
Getting atomic writes right
Getting atomic writes right
Suites, scopes, and lifetimes
Suites, scopes, and lifetimes
1
Swift-style map and filter views
Swift-style map and filter views
1
Inline (bytecode) assembly
Inline (bytecode) assembly
Why Python (or any decent language) doesn't need blocks
Why Python (or any decent language) doesn't need blocks
18
SortedContainers
SortedContainers
1
Fixing lambda
Fixing lambda
2
Arguments and parameters, under the covers
Arguments and parameters, under the covers
pip, extension modules, and distro packages
pip, extension modules, and distro packages
Python doesn't have encapsulation?
Python doesn't have encapsulation?
3
Grouping into runs of adjacent values
Grouping into runs of adjacent values
dbm: not just for Unix
dbm: not just for Unix
How to use your self
How to use your self
1
Tkinter validation
Tkinter validation
7
What's the deal with ttk.Frame.__init__(self, parent)
What's the deal with ttk.Frame.__init__(self, parent)
1
Does Python pass by value, or by reference?
Does Python pass by value, or by reference?
9
"if not exists" definitions
"if not exists" definitions
repr + eval = bad idea
repr + eval = bad idea
1
Solving callbacks for Python GUIs
Solving callbacks for Python GUIs
Why your GUI app freezes
Why your GUI app freezes
21
Using python.org binary installations with Xcode 5
Using python.org binary installations with Xcode 5
defaultdict vs. setdefault
defaultdict vs. setdefault
1
Lazy restartable iteration
Lazy restartable iteration
2
Arguments and parameters
Arguments and parameters
3
How grouper works
How grouper works
1
Comprehensions vs. map
Comprehensions vs. map
2
Basic thread pools
Basic thread pools
Sorted collections in the stdlib
Sorted collections in the stdlib
4
Mac environment variables
Mac environment variables
Syntactic takewhile?
Syntactic takewhile?
4
Can you optimize list(genexp)
Can you optimize list(genexp)
MISRA-C and Python
MISRA-C and Python
1
How to split your program in two
How to split your program in two
How methods work
How methods work
3
readlines considered silly
readlines considered silly
6
Comprehensions for dummies
Comprehensions for dummies
Sockets are byte streams, not message streams
Sockets are byte streams, not message streams
9
Why you don't want to dynamically create variables
Why you don't want to dynamically create variables
7
Why eval/exec is bad
Why eval/exec is bad
Iterator Pipelines
Iterator Pipelines
2
Why are non-mutating algorithms simpler to write in Python?
Why are non-mutating algorithms simpler to write in Python?
2
Sticking with Apple's Python 2.7
Sticking with Apple's Python 2.7
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.