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.