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

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed.

5

I haven't posted anything new in a couple years (partly because I attempted to move to a different blogging platform where I could write everything in markdown instead of HTML but got frustrated—which I may attempt again), but I've had a few private comments and emails on some of the old posts, so I

6

Looking before you leap

Python is a duck-typed language, and one where you usually trust EAFP ("Easier to Ask Forgiveness than Permission") over LBYL ("Look Before You Leap").

1

Background

Currently, CPython’s internal bytecode format stores instructions with no args as 1 byte, instructions with small args as 3 bytes, and instructions with large args as 6 bytes (actually, a 3-byte EXTENDED_ARG followed by a 3-byte real instruction).

6

If you want to skip all the tl;dr and cut to the chase, jump to Concrete Proposal.

8

Many people, when they first discover the heapq module, have two questions:

Why does it define a bunch of functions instead of a container type? Why don't those functions take a key or reverse parameter, like all the other sorting-related stuff in Python? Why not a type?

At the abstract level, it'

1

Currently, in CPython, if you want to process bytecode, either in C or in Python, it’s pretty complicated.

The built-in peephole optimizer has to do extra work fixing up jump targets and the line-number table, and just punts on many cases because they’re too hard to deal with.

3

One common "advanced question" on places like StackOverflow and python-list is "how do I dynamically create a function/method/class/whatever"? The standard answer is: first, some caveats about why you probably don't want to do that, and then an explanation of the various ways to do it when you reall

1

A few years ago, Cesare di Mauro created a project called WPython, a fork of CPython 2.6.4 that “brings many optimizations and refactorings”. The starting point of the project was replacing the bytecode with “wordcode”. However, there were a number of other changes on top of it.

1

Many languages have a for-each loop.

4

When the first betas for Swift came out, I was impressed by their collection design. In particular, the way it allows them to write map-style functions that are lazy (like Python 3), but still as full-featured as possible.

2

In a previous post, I explained in detail how lookup works in Python.

2

The documentation does a great job explaining how things normally get looked up, and how you can hook them.

But to understand how the hooking works, you need to go under the covers to see how that normal lookup actually happens.

When I say "Python" below, I'm mostly talking about CPython 3.5.

7

In Python (I'm mostly talking about CPython here, but other implementations do similar things), when you write the following:

def spam(x): return x+1 spam(3) What happens?

Really, it's not that complicated, but there's no documentation anywhere that puts it all together.

2

I've seen a number of people ask why, if you can have arbitrary-sized integers that do everything exactly, you can't do the same thing with floats, avoiding all the rounding problems that they keep running into.

2

In a recent thread on python-ideas, Stephan Sahm suggested, in effect, changing the method resolution order (MRO) from C3-linearization to a simple depth-first search a la old-school Python or C++.

1

Note: This post doesn't talk about Python that much, except as a point of comparison for JavaScript.

Most object-oriented languages out there, including Python, are class-based. But JavaScript is instead prototype-based.

1

About a year and a half ago, I wrote a blog post on the idea of adding pattern matching to Python.

I finally got around to playing with Scala semi-seriously, and I realized that they pretty much solved the same problem, in a pretty similar way to my straw man proposal, and it works great.

About a year ago, Jules Jacobs wrote a series (part 1 and part 2, with part 3 still forthcoming) on the best collections library design.

1

In three separate discussions on the Python mailing lists this month, people have objected to some design because it leaks something into the enclosing scope. But "leaks into the enclosing scope" isn't a real problem.

2

There's a lot of confusion about what the various kinds of things you can iterate over in Python. I'll attempt to collect definitions for all of the relevant terms, and provide examples, here, so I don't have to go over the same discussions in the same circles every time.

8

Python has a whole hierarchy of collection-related abstract types, described in the collections.abc module in the standard library. But there are two key, prototypical kinds. Iterators are one-shot, used for a single forward traversal, and usually lazy, generating each value on the fly as requested.

2

There are a lot of novice questions on optimizing NumPy code on StackOverflow, that make a lot of the same mistakes. I'll try to cover them all here.

What does NumPy speed up?

Let's look at some Python code that does some computation element-wise on two lists of lists.

2

When asyncio was first proposed, many people (not so much on python-ideas, where Guido first suggested it, but on external blogs) had the same reaction: Doing the core reactor loop in Python is going to be way too slow. Something based on libev, like gevent, is inherently going to be much faster.

Let's say you have a good idea for a change to Python.

1

There are hundreds of questions on StackOverflow that all ask variations of the same thing. Paraphrasing:

lst is a list of strings and numbers. I want to convert the numbers to int but leave the strings alone.

2

In Haskell, you can section infix operators. This is a simple form of partial evaluation. Using Python syntax, the following are equivalent:

(2*) lambda x: 2*x (*2) lambda x: x*2 (*) lambda x, y: x*y So, can we do the same in Python?

Grammar

The first form, (2*), is unambiguous.

1

Many people—especially people coming from Java—think that using try/except is "inelegant", or "inefficient". Or, slightly less meaninglessly, they think that "exceptions should only be for errors, not for normal flow control".

These people are not going to be happy with Python.

2

If you look at Python tutorials and sample code, proposals for new language features, blogs like this one, talks at PyCon, etc., you'll see spam, eggs, gouda, etc. all over the place.

Most control structures in most most programming languages, including Python, are subordinating conjunctions, like "if", "while", and "except", although "with" is a preposition, and "for" is a preposition used strangely (although not as strangely as in C…).

There are two ways that some Python programmers overuse lambda. Doing this almost always mkes your code less readable, and for no corresponding benefit.

1

Some languages have a very strong idiomatic style—in Python, Haskell, or Swift, the same code by two different programmers is likely to look a lot more similar than in Perl, Lisp, or C++.

There's an advantage to this—and, in particular, an advantage to you sticking to those idioms.

1

Python doesn't have a way to clone generators.

At least for a lot of simple cases, however, it's pretty obvious what cloning them should do, and being able to do so would be handy. But for a lot of other cases, it's not at all obvious.

5

Every time someone has a good idea, they believe it should be in the stdlib. After all, it's useful to many people, and what's the harm? But of course there is a harm.

3

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>()

11
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.