[Python-ideas] Wild idea about mutability

Sven R. Kunze srkunze at mail.de
Mon Jun 6 06:44:10 EDT 2016


On 06.06.2016 09:55, Robert Collins wrote:
> 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.

That's what I thought as well. So, I see a huge benefit for enforced 
immutability when it comes to reducing errors and not re-inventing the 
wheel.


Thinking this further, __init__ would be the only function to change the 
state of an immutable object. Once created, it will never change. 
Immutable also implies hashability IMHO. Moreover, immutable object 
would not be allowed to query data from global/external variables as 
those can change and would change the observable state of the object 
without the object noticing. So, the allowed way of creating a state for 
an immutable object would be using a new container as you did (by 
defining self._cache) and store immutable objects only there. Would this 
make sense?

Sven

> 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