Tuples and immutability

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 13 00:20:46 CET 2014

On Tue, 11 Mar 2014 17:06:43 -0600, Ian Kelly wrote:

> On Tue, Mar 11, 2014 at 10:46 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>>> There are a number of possible solutions.  One possibility would be to
>>> copy the Circle as an Ellipse and return the new object instead of
>>> mutating it. Then you have the situation where, given a mutable object
>>> x that satisfies isinstance(x, Ellipse), the stretch method *may* be
>>> able to update the object in-place, or it *may* not.
>> That is a really lousy design. Of course we are free to create classes
>> with ugly, inconsistent, stupid or unworkable APIs if we like. Python
>> won't stop us:
> That's true but irrelevant to my point, which was to counter the
> assertion that mutable types can always be assumed to be able to perform
> operations in-place.

"Always"? Not so fast.

This is Python. We have freedom to abuse nearly everything, and if you 
want to shoot yourself in the foot, you can. With the exception of a 
handful of things which cannot be overridden (e.g. None, numeric 
literals, syntax) you cannot strictly assume anything about anything. 
Python does not enforce that iterators raise StopIteration when empty, or 
that indexing beyond the boundaries of a sequence raises IndexError, or 
that __setitem__ of a mapping sets the key and value, or that __len__ 
returns a length.

Augmented assignment is no different. The docs describe the intention of 
the designers and the behaviour of the classes that they control, so with 
standard built-in classes like int, str, list, tuple etc. you can safely 
assume that mutable types will perform the operation in place and 
immutable types won't, but with arbitrary types from some arbitrarily 
eccentric or twisted programmer, who knows what it will do?

Steven D'Aprano

More information about the Python-list mailing list