Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make an immutable object in Python?
    text
    copied!<p>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 <a href="https://docs.python.org/3/reference/datamodel.html#object.__setattr__" rel="noreferrer"><code>__setattr__</code></a>, because then you can't even set attributes in the <a href="https://docs.python.org/3/reference/datamodel.html#object.__init__" rel="noreferrer"><code>__init__</code></a>. Subclassing a tuple is a trick that works:</p> <pre><code>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 "&lt;Immutable {0}, {1}&gt;".format(self.a, self.b) def __setattr__(self, *ignored): raise NotImplementedError def __delattr__(self, *ignored): raise NotImplementedError </code></pre> <p>But then you have access to the <code>a</code> and <code>b</code> variables through <code>self[0]</code> and <code>self[1]</code>, which is annoying.</p> <p>Is this possible in Pure Python? If not, how would I do it with a C extension?</p> <p>(Answers that work only in Python 3 are acceptable).</p> <p><strong>Update:</strong> </p> <p>So subclassing tuple is the way to do it in Pure Python, which works well except for the additional possibility of accessing the data by <code>[0]</code>, <code>[1]</code> etc. So, to complete this question all that is missing is howto do it "properly" in C, which I suspect would be quite simple, by just not implementing any <code>geititem</code> or <code>setattribute</code>, etc. But instead of doing it myself, I offer a bounty for that, because I'm lazy. :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload