Immutability and Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Oct 29 19:14:50 EDT 2012


On Mon, 29 Oct 2012 15:45:59 -0700, Chris Kaynor wrote:

> On Mon, Oct 29, 2012 at 3:30 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> On Mon, 29 Oct 2012 17:05:07 +0000, andrea crotti wrote:
>>
>>> I meant how do I create new immutables classes myself, I guess that's
>>> possible writing C extensions but I don't see in pure Python..
>>
>> Well, you can't *quite* make a truly immutable class in pure-Python,
>> because if *your* Python code can manipulate the class during
>> construction then so can the caller's Python code after construction.
>>
>> The trivial way to make an immutable class in Python is to inherit from
>> an already immutable class and add behaviour but no state:
>>
>> class MyInt(int):
>>     def inc(self):
>>         return self.__class__(self + 1)
>>
>>
>> Otherwise, you can add private state and rely on the caller not
>> shooting themselves in the foot by accessing single-underscore names,
>> use properties to protect private state, etc.
>>
>>
> You'd also need to add __slots__ = () to the class definition to make it
> immutable. Otherwise they still can shoot themselves in the foot by
> adding new attributes.

"Doctor, it hurts when I do this."

"Then don't do that."


I'm not a big fan of preventatively using __slots__ merely to prevent the 
caller from tagging an object with extra data. Why do you care if the 
caller sticks a postit note on the object? It doesn't hurt the object, 
and if the caller loses track of which object has a postit note, that's 
their responsibility, not yours.

I often wish I could sick an attribute on built-ins, e.g. after 
calculating some numeric result as a float, stick an error estimate on 
it. Callers who care about the error estimate can inspect it; those who 
don't, will never even notice it.

If you have a good reason for using __slots__, then go right ahead. 
Otherwise, don't be paternalistic. This is Python, we have the right to 
shoot ourselves in the foot if we like.


-- 
Steven



More information about the Python-list mailing list