Making immutable instances

Mike Meyer mwm at mired.org
Fri Nov 25 20:33:43 CET 2005


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
> Mike Meyer <mwm at mired.org> writes:
>> There isn't a standard serialize method in Python, so I don't know how
>> you want to define it.
>> I can think of perfectly reasonable definitions
>> of serialize where obj.serialize() won't always return the same string
>> on an immutable object, even if you don't allow adding attributes.
> Fair enough.  How's this:
>
>    a = ImmutableObject()
>    b = deepcopy(a)
>    assert a == b  # a and b start out equal
>    .... do stuff ....
>    # since a and b are immutable, they should still be equal
>    # no matter what has happened above
>    assert a == b
>
> If you've added attributes to a but not to b, they should compare
> unequal, breaking immutability.

Why should they compare unequal just because you add an attribute?
Nothing says all attributes have to be involved in an equality
comparison. In fact, Python classes by default ignore all attributes
when doing an equality comparison. In order to compare attributes, you
have to provide an __eq__ method (or __cmp__, but we'll ignore
that). It can't mention your new attribute, because it doesn't exist
unless you add it. So your final assertion will be true even after
adding a new attribute.

Of course, there's a fundamental flaw in your definition of
"immutable", in that there are immutable objects - tuples - for which
the condition t1 == t2 is *not* a constant. Tuples can hold mutable
objects, meaning you can change those. Doing so will make a tuple not
compare equal to a copy of the state prior to changing the contents of
the tuple.

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list