Making immutable instances

Mike Meyer mwm at mired.org
Thu Nov 24 11:44:16 EST 2005


Ben Finney <bignose+hates-spam at benfinney.id.au> writes:
> I'm looking for a "consenting adults" restriction: classes will have
> immutable instances only where it makes sense from the class protocol.
> I'm not going to lose sleep over users who go looking for trouble.

I think you're defining immutable differently than I do. Python
already supports attributes that clients can't rebind. You can make an
instance in which all attributes have that property. However
attributes added by a client aren't really yours. They don't change
the immutability of your attributes, or affect the behavior of your
class in any way. Such attributes don't really belong to your class;
they belong to the client.

Even in full B&D languages, it's trivial to overcome this restriction
with a subclass:

>>> i = int()
>>> i
0
>>> i.foo = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'int' object has no attribute 'foo'
>>> class Aint(int): pass
... 
>>> m = Aint()
>>> m
0
>>> m.foo = 1
>>> m.foo
1
>>> 

The extra class is the kind of boilerplate that Python in general has
so little of, and B&D languages so much of. In Python, I can even fix
it so *your* code uses my wrapped version:

import Finney
class Addable(Finnney.Immutable): pass
Finney.Immutable = Addable

Which means that from now on *your* code that tries to create
Immutables will actually get Addables. The inability to do this in B&D
languages is - well, painfull. That Python doesns't require the
boilerplate in a good thing.

        <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