How to Make a Python Class Immutable

In object-oriented programming there are objects we can change (mutable) and objects we cannot change (immutable). In Python we are given some built-in immutable object types, numbers, booleans, strings, tuples, and frozensets. Immutable objects are useful for preventing aliasing, lowering copying costs, improving run-time efficiency, and when you just don't want anyone to be able to change your object's attributes.

While learning how to use the web framework Flask, its ImmutableMultidict data structure caught my attention. Not just because of its humorous name, but also because it declared its self immutable while just being a python class. I set out to see how Python allows classes to protect themselves from changes.

Inside Python classes, there are many built in methods available that you can define inside your class that dictate the inner workings of the class and how they behave. Here is a really good guide for these "magic" methods



The __setattr__ Method

The __setattr__ method can be defined inside your class and will redirect any attempt to change its attributes to the code in this method. An important thing to consider is that this will prevent you from even setting instance attributes in the __init__ method unless you have a workaround inside __setattr__.

import inspect

class Immutable(object):
    """Inherit this class to make your class immutable"""
    def __setattr__(self, *args):
        if inspect.stack()[1][3] == '__init__':
            object.__setattr__(self, *args)
        else:
            raise TypeError('Cannot modify immutable instance')


Here I handled the __init__ problem by using inspect.stack()[1][3] to check if the name of the calling method is __init__ and if true, calling the base class object's __setattr__ method to allow the attributes to be set. If any method not named __init__ attempts to change the value of the object, it will raise an error, preventing the change.


The __delattr__ Method

The __delattr__ method can be similarly used to prevent the object's attributes from being deleted. We could repeat all the code from __setattr__ inside a __delattr__ method or we could be civilized and add one simple line to our class to assign the __delattr__ method to __setattr__.

    __delattr__ = __setattr__

Inherit the Immutable Class

Now all you have to do is have your class inherit the Immutable class (after importing immutable.py from my github) and it will make your object immutable.

from immutable import Immutable

class Test_Immute(Immutable):
    def __init__(self, x):
    self.x = x


#this initializes successfully
new_obj = Test_Immute(6)
print(new_obj.x)
#this throws error
new_obj.x = 7



With this simple class to inherit, we have the immutable part of the ImmutableMultidict. My next post will delve into how we can make our own Multidict and what we can use it for.



Comments

  1. Nice post. I learned some new information. Thanks for sharing.

    zhosters
    Guest posting sites

    ReplyDelete
  2. EasyUEFI Enterprise 4.9.2.0 Crack is used for creating, deleting, modifying, configuring, and repairing EFI / UEFI startup options.Easyuefi Crack

    ReplyDelete
  3. Happy NYE Wishes | 2023 Messages | Inspirational Quotes | Blessings | Bible Verses | Funny | Family | Friends | Boss & Co-workers | Text/SMS .May God Bless You With Good Health And Long Life Quotes

    ReplyDelete
  4. The RTP predetermines the likelihood, and this cannot be affected. However, as is the case in buying anything pre-owned, you run the danger of getting the machine plagued with issues. It’s value making certain a 메리트카지노 slot machine is in working order earlier than committing to buy a pre-owned mannequin, except you’re able to fixing it.

    ReplyDelete
  5. Nice blog.Keep up with your good work.
    Python classes in Pune

    ReplyDelete
  6. To make a Python class immutable, you can override methods like `__setattr__` to prevent attribute modification. This is akin to a Blade runner coat designed to withstand wear and tear without losing its form. Just as the coat remains unchanged, an immutable class ensures that its attributes cannot be altered after creation.

    ReplyDelete

Post a Comment

Popular Posts