OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to make an immutable object in Python?

  • Thread starter Thread starter Lennart Regebro
  • Start date Start date
L

Lennart Regebro

Guest
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:

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 "<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.
<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="nofollow 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="nofollow 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 "<Immutable {0}, {1}>".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? Answers that work only in Python 3 are acceptable.</p>
 

Latest posts

G
Replies
0
Views
1
Gamal Othman
G
Top