Making immutable instances

Giovanni Bajo noway at sorry.com
Thu Nov 24 20:17:09 EST 2005


Mike Meyer wrote:

> And I have no problems with that. If you believe your class should
> throw an error if someone calls an instances pop() method when it's
> empty, do so.
>
> Likewise, if you want to make it so a client can't change your
> attributes, feel free to do so.
>
> However, when you prevent a client from adding an attribute, you're
> not merely making your objects immutable, you're making them
> static. Python isn't a static language, it's a dynamic language. I
> consider parts of it that are static to be warts.

I always thought that adding an attribute was just as bad as changing the
attributes, for an immutable object. But I now see your point (eventually!),
they are pretty different issues.

But, whatever attribute you add to the instance, it should *also* be immutable
(so that, in other words, wouldn't be so different than carrying around a tuple
with the original instance and the added attribute). This said, I think I
devise that a language support for enforcing immutability could allow adding
attributes to instance -- as long as those attributes then become immutable as
well.

>>> I'm not sure it's more important than
>>> things like interned strings and the sharing of small integers.
>>> Most
>>> of the discussion of immutables here seems to be caused by newcomers
>>> wanting to copy an idiom from another language which doesn't have
>>> immutable variables. Their real problem is usually with binding, not
>>> immutability.
>> I'm not such a newcomer, but (how funny) Python is *the* language
>> that introduced me to the concept of immutable objects and their
>> importance in design :)
>
> Well, that would explain why you think it's so important - it's where
> you first encountered it.

Yes. But I'm familiar with different object semantics, and I found the
immutable objects to be a pretty good replacement of value semantics, and to
implement a kind-of pass-by-value convention in a language which only has
references.

> I'd argue that it's no more important than
> identity - which is what I was searching for when I talked about
> interned strings sharing small integers. There are builtin types that
> preserve identity for equal instances, at least under some
> conditions. There are no constructs for helping you do that with
> user-defined objects. Should we add them for the sake of
> orthogonality? I don't think so - not without a good use case.

I don't think identity is important for immutable objects (as I wrote
elsewhere), so I don't think adding language constucts for this would prove
useful. Instead, immutable objects *are* common, and we still miss a way to
mark them as such.
-- 
Giovanni Bajo





More information about the Python-list mailing list