Making immutable instances

Giovanni Bajo noway at sorry.com
Thu Nov 24 19:29:14 EST 2005


Mike wrote:

>> 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.
>
> Why is it "surely" a bug?  It is arguable whether adding new
> attributes (vs. changing those that are already there) is, in fact,
> mutation.

If we agree that *changing* attributes is a bug for those classes, we're
already a step beyond in this discussion :)

About adding attributes, I agree that it's kind of a grey area. Per-se, there
is nothing wrong. My experience is that they give the user a false expectation
that the object can be modified. It ends up with an object with attributes
which can't be modified because that'd break invariants, and others which are
freely modificable.

In fact, the only thing that you are adding an attribute to *that* instance,
and not to all the *equivalent* instances (by definition of __hash__/__eq__) is
questionable and bug-prone. You might end up *thinking* you have that very
instance around, while you don't. In fact, with immutable objects, you are not
supposed to think in terms of instances, but rather of values. When I see a
string like "foobar" I don't care if it's the same instance of a "foobar" I saw
before. If I could add an attribute to "foobar", I might end up believing that
whenever I see a "foobar" around, it will have that attribute.

As you said, Python has rich data structures which lets you still find good
ways to carry around additional information. So why trying so hard to get into
trouble?

> It sounds like what you may want are opaque objects where you can
> control access better

No that's a different issue.  One example of my immutable classes is Point2D
(two attributes: x/y). Having it immutable gives it many useful properties,
such as a real value semantic.
-- 
Giovanni Bajo





More information about the Python-list mailing list