[Python-ideas] Wild idea about mutability

Steven D'Aprano steve at pearwood.info
Mon Jun 6 10:40:34 EDT 2016


On Mon, Jun 06, 2016 at 12:44:10PM +0200, Sven R. Kunze wrote:

> 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.

Python classes have supported "cooperative immutability" for 20+ years. 
For example, the pure Python Decimal and Fraction classes are immutable 
only by convention, if you modify the _private attributes you can change 
them. And yet they work fine.

I'm not saying that "real immutability" wouldn't be nice to have, but I 
think that describing it as huge benefit is possible overstating it.


> Thinking this further, __init__ would be the only function to change the 
> state of an immutable object. Once created, it will never change. 

How would you enforce that?


> Immutable also implies hashability IMHO.

That's incorrect. We all agree that tuples are immutable, I trust.

py> t = (1, 2, {}, 3)
py> hash(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'


Immutable collections are only hashable if all their components are 
hashable.


> 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.

How would you enforce that?


> 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?

I don't understand this paragraph, sorry.


-- 
Steve


More information about the Python-ideas mailing list