Making immutable instances

Giovanni Bajo noway at sorry.com
Thu Nov 24 19:20:43 EST 2005


Björn Lindström wrote:

>> My feeling is that you're trying to get too much out of my words. I'm
>> not trying to handcuff anyone. You seem to concentrate on me trying
>> to avoid people adding attributes to my precious objects. It's not
>> that. If I write a class and want it to be immutable, it is because
>> it has to be so. If I write a queue class and I say that people
>> shouldn't call pop() if it's empty, I mean it. If I enforce it with a
>> RuntimeError, I'm not thinking I'm handcuffing someone. I don't see a
>> ImmutableError to be so different from it.
>
> But why would you call it that, when the object isn't actually
> implemented as immutable?

I think you misunderstood my message. I'm saying that an ImmutableError
wouldn't be a much different form of self-checking compared to the usual
TypeError/ValueError/RuntimeError you get when you pass wrong values/types to
methods/functions, or you violate invariants of objects. This has nothing to do
with dynamism, duck typing, dynamic binding and whatnot. Some objects have deep
invariants which can't be broken.

Why do you think we have a frozenset, for instance? By Mike's argument, we
shouldn't have it. And we should be able to use a regular mutable set as
dictionary key. Unittests will catch errors. Instead, we got two classes
instead of one, immutability is *enforced*, and sets can't be used as
dictionary keys. This is all good in my opinion, and follows the good rule of
"catch errors early".

> Throw an exception that describes why it doesn't make sense to change
> that particular object instead.

*How* can I do? There is no language construct which lets me specifies an
exception to throw whenever someone modifies my object. *Even* if I got partial
support for immutable types (like __new__  which can be used to initialize
immutable objects).

> As I said before, I think you're confusing the (in Python pretty
> non-existent) concept of encapsulation with Python's immutable types,
> which are immutable because the implementation demands it. (A fact I
> hope will disappear at some point.)

You seriously believe that strings, integers and tuples are immutable because
of implementation details? I believe they are part of a language design -- and
a good part of it.
-- 
Giovanni Bajo





More information about the Python-list mailing list