Making immutable instances

Giovanni Bajo noway at sorry.com
Thu Nov 24 03:00:07 EST 2005


Mike wrote:

>> How can a (user-defined) class ensure that its instances are
>> immutable, like an int or a tuple, without inheriting from those
>> types?
>>
>> What caveats should be observed in making immutable instances?
>
> IMHO, this is usually (but not always) a mistake. (If you're
> programming a missle guidance system, or it makes your program go
> faster it's not a mistake :))
> So are PRIVATE, CONST (all types), SEALED, FINAL, etc -- even the best
> programmer doesn't foresee what a user will want to do to make best
> use of his components, and many a time I've been annoyed (in Java and
> MS frameworks) by not being able to access/modify/subclass a
> member/class that I know is there because it has to be there (or
> because I can see it in the debugger), but it's not accessable
> because the programmer was overly clever and had been to OOP school.

There's a big difference. An immutable object has a totally different semantic,
compared to a mutable object. If you document it to be immutable, and maybe
even provide __eq__ /__hash__, adding attributes from it is surely an user bug.
And surely a bug for which I'd expect an exception to be raised.

Sometimes, I play with some of my objects and I have to go back and check
documentation whether they are immutable or not, to make sure I use the correct
usage pattern. That's fine, this is what docs are for, but couldn't Python give
me some way to enforce this so that, if I or some other dev do the mistake, it
doesn't go unnoticed?
-- 
Giovanni Bajo





More information about the Python-list mailing list