What is the difference between 'type' and 'class'?

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Mon Jun 21 22:13:25 EDT 2010


On Mon, 21 Jun 2010 15:43:01 -0700, Stephen Hansen wrote:

> many types are fundamentally immutable(i.e., ints, strings), and its
> awful hard to make an immutable class.

It's really simple if you can inherit from an existing immutable class.

class K(tuple):
    pass


Of course, that lets you add attributes to K instances, which might not 
be what you want. So, in full knowledge that many Python programmers will 
laugh and point at you, you can (ab)use __slots__ to remove that ability:


>>> class K(tuple):
...     __slots__ = []
...
>>> t = K((1,2,3))
>>> t[0] = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'K' object does not support item assignment
>>> t.x = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'K' object has no attribute 'x'



The tricky part is making an immutable class from scratch, i.e. 
inheriting from object. For a fairly large, complex example, you can see 
how the Decimal class does it -- basically uses read-only properties for 
public attributes, and hope that nobody modifies the private attributes. 
(If they do, they deserve whatever pain they get.)

Or you can do something like this:

http://northernplanets.blogspot.com/2007/01/immutable-instances-in-python.html


There's probably no way to make pure Python classes completely immutable 
without inheriting from an already immutable class. Pity.


-- 
Steven



More information about the Python-list mailing list