Tuples and immutability

Ian Kelly ian.g.kelly at gmail.com
Mon Mar 10 04:35:36 EDT 2014


On Sun, Mar 9, 2014 at 8:37 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sun, 09 Mar 2014 17:42:42 -0600, Ian Kelly wrote:
>
>> On Sun, Mar 9, 2014 at 4:03 PM, Gregory Ewing
>> <greg.ewing at canterbury.ac.nz> wrote:
>
>>> Note that it says "when possible", not "if the implementation feels
>>> like it".
>>
>> That's quite vague, and not much stronger a guarantee than "maybe". It's
>> technically "possible" for this augmented assignment to be performed in
>> place:
>>
>> x = 12
>> x += 4
>>
>> But it's not done in-place, because ints are meant to be immutable.
>
> That's incorrect. Ints aren't merely "meant" to be immutable, which
> implies that's it's optional, they are defined by the language
> specification and the reference implementation as immutable. Any
> interpreter where ints are mutable *is not Python*.

That's true, but is beside the point, which is that "when possible" is
not very meaningful.

>> In any case, this means that whether the operation is actually performed
>> in-place is an implementation detail -- if not of the Python
>> implementation then at least of the class -- and not something the user
>> should take for granted.
>
> Whether += operates in place or not is part of the interface of the
> class, not the implementation.
>
> Would you say that whether list.append operates in place or creates a new
> list is an implementation detail? Whether str.upper() creates a new
> string or modifies the existing one in place?

Of course not.  list.append is documented as modifying the list.
str.upper is documented as returning a copy of the string.

> Mutability versus
> immutability is part of the interface, not implementation, not
> withstanding that somebody could create an alternative class with the
> opposite behaviour: a MutableStr, or ImmutableList.

If the in-place behavior of += is held to be part of the interface,
then we must accept that += is not polymorphic across mutable and
immutable types, which in my mind largely* defeats the purpose of
having it.  After all, there should be one -- and preferably only one
-- obvious way to do it.  If you want in-place concatenation, the
obvious way to do it is by calling extend.  If you want copy
concatenation, the obvious way to do it is with the + operator.  Why
then should not just mutable sequences but immutable sequences as well
even offer the += operator?

* The one exception I can think of is numpy, where there is no more
obvious way to do in-place addition, and in that context I would
consider the in-place behavior to be part of the interface.



More information about the Python-list mailing list