[Python-ideas] Wild idea about mutability

Robert Collins robertc at robertcollins.net
Mon Jun 6 03:55:55 EDT 2016


On 6 June 2016 at 19:05, Sven R. Kunze <srkunze at mail.de> wrote:
> On 02.06.2016 16:18, Joao S. O. Bueno wrote:
>>
>> Just remembering that one is free to implement whatever "switchable"
>> containers one wants in the language as it is now - no need to force
>> (full or slightly) incompatible  changes that imply on performance
>> degradation onto every single Python user for a feature that was not
>> needed up to this day.
>>
>> Implementing this in  sequence-abc, and mapping-abc classes is trivial.
>>
>> A reasonable request for the language could be exactly to allow a
>> "__mutable__" property on the sequence, container and mapping
>> protocols, and a "mutable" built-in callable, that in the absence of
>> "__mutable__" could check for the methods signature (if it does not
>> have "__mutable__" but has "__setitem__" , then mutable(obj) returns
>> True, for example).
>
>
> Is __setitem__ the only way to change an object?

No. Trivially a method on an extension object can be storing state in
a C struct. Let trivially:

Class IsThisMutable:
    def __init__(self):
        self._cache = {}

    def random(self):
        self._cache[len(self._cache)] = random.random()
        return self._cache[len(self._cache)-1]

    def size(self):
        return len(self._cache)

this has interior mutability - it uses __setitem__ on self._cache to
track that state. You could remove __setitem__ from IsThisMutable
instances post construction and it would still be getting mutated.

-Rob


More information about the Python-ideas mailing list