How Can We Achieve True Immutability in Python?

Mary-Kate Olsen
Release: 2024-10-25 08:25:28
Original
607 people have browsed it

How Can We Achieve True Immutability in Python?

Making Immutable Objects in Python

Creating immutable objects in Python can pose challenges. Simply overriding setattr is insufficient, as attributes cannot be set during initialization. A commonly employed solution is to subclass a tuple, as demonstrated below:

<code class="python">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>
Copy after login

However, this approach grants access to the a and b attributes through self[0] and self[1], which can be inconvenient.

To achieve pure Python immutability, another alternative exists:

<code class="python">Immutable = collections.namedtuple("Immutable", ["a", "b"])</code>
Copy after login

This method generates a type with the desired behavior, utilizing slots and inheriting from tuple. It offers the benefits of compatibility with pickle and copy, but still allows for accessing attributes via [0] and [1].

The above is the detailed content of How Can We Achieve True Immutability in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!