Tuples and immutability
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Mar 9 22:37:05 EDT 2014
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*.
> 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? 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.
--
Steven D'Aprano
http://import-that.dreamwidth.org/
More information about the Python-list
mailing list