[Python] How to make an immutable object in Python?

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página