How to make an immutable object in Python?
Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override __setattr__
, because then you can't even set attributes in the __init__
. Subclassing a tuple is a trick that works:
class Immutable(tuple):
def __new__(cls, a, b):
return tuple.__new__(cls, (a, b))
@property
def a(self):
return self[0]
@property
def b(self):
return self[1]
def __str__(self):
return "<Immutable {0}, {1}>".format(self.a, self.b)
def __setattr__(self, *ignored):
raise NotImplementedError
def __delattr__(self, *ignored):
raise NotImplementedError
But then you have access to the a
and b
variables through self[0]
and self[1]
, which is annoying.
Is this possible in Pure Python? If not, how would I do it with a C extension?
(Answers that work only in Python 3 are acceptable).
Update:
As of Python 3.7, the way to go is to use the @dataclass
decorator, see the newly accepted answer.
Yet another solution I just thought of: The simplest way to get the same behaviour as your original code is
Immutable = collections.namedtuple("Immutable", ["a", "b"])
It does not solve the problem that attributes can be accessed via [0]
etc., but at least it's considerably shorter and provides the additional advantage of being compatible with pickle
and copy
.
namedtuple
creates a type similar to what I described in this answer, i.e. derived from tuple
and using __slots__
. It is available in Python 2.6 or above.
The easiest way to do this is using __slots__
:
class A(object):
__slots__ = []
Instances of A
are immutable now, since you can't set any attributes on them.
If you want the class instances to contain data, you can combine this with deriving from tuple
:
from operator import itemgetter
class Point(tuple):
__slots__ = []
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
x = property(itemgetter(0))
y = property(itemgetter(1))
p = Point(2, 3)
p.x
# 2
p.y
# 3
Edit: If you want to get rid of indexing either, you can override __getitem__()
:
class Point(tuple):
__slots__ = []
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
@property
def x(self):
return tuple.__getitem__(self, 0)
@property
def y(self):
return tuple.__getitem__(self, 1)
def __getitem__(self, item):
raise TypeError
Note that you can't use operator.itemgetter
for the properties in thise case, since this would rely on Point.__getitem__()
instead of tuple.__getitem__()
. Fuerthermore this won't prevent the use of tuple.__getitem__(p, 0)
, but I can hardly imagine how this should constitute a problem.
I don't think the "right" way of creating an immutable object is writing a C extension. Python usually relies on library implementers and library users being consenting adults, and instead of really enforcing an interface, the interface should be clearly stated in the documentation. This is why I don't consider the possibility of circumventing an overridden __setattr__()
by calling object.__setattr__()
a problem. If someone does this, it's on her own risk.