Immutable Objects in Python: Beyond Basic Solutions
While the standard tuple class provides immutability, this article explores more advanced techniques for creating immutable objects in pure Python or with C extensions.
Overriding __setattr__: A Limited Approach
One common solution is to override the setattr method. However, this prevents attribute setting even in the init function. Therefore, it may not be suitable for all scenarios.
Subclassing Tuple: A Partial Solution
Another approach is to subclass tuple, providing a custom new method and properties for accessing attributes. However, this method doesn't completely prevent attribute access through self[0] and self[1], which can be inconvenient.
The namedtuple Solution: Simplicity and Compatibility
A simpler and more robust solution is to use the namedtuple class from the Python collections module:
Immutable = collections.namedtuple("Immutable", ["a", "b"])
Similar to the previous technique, this creates a type derived from tuple and uses __slots__. It offers several advantages:
Conclusion
The namedtuple class provides a convenient and efficient way to create immutable objects in Python. It's a viable alternative to более advanced techniques and offers additional benefits such as serialization compatibility.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3