How to make an immutable instance

Tim Peters tim.peters at gmail.com
Thu Jun 17 23:31:52 EDT 2004


[Batista, Facundo]
> I'm working on Decimal, and one of the PEP requests is Decimal to be
> immutable.

I wouldn't worry about this.  The most important thing about
immutability is that we promise the *implementation* of Decimal won't
mutate a user-visible Decimal object.  There's no way to prevent a
determined idiot from mutating one themself in Python, and trying
anyway leads to slower, bigger, uglier, more obscure code.

When/if Decimal is recoded in C, it will be easy to make it "truly
immutable".  If you think you have to try in Python anyway, then yes,
read-only properties are the intended way to get an idiot-resistant
approximation to immutability.

It should be enough (IMO) to give Decimal data members names with a
single leading underscore.  That's fair warning that users aren't
supposed to muck with them.  I've lived to regret it every time I've
given a data member a "private name" (two leading underscores) --
that's no better at truly stopping determined users from cheating
anyway, and has invariably created problems over time when refactoring
code.




More information about the Python-list mailing list