DEV Community

Discussion on: Immutable objects in Python

Collapse
 
lyfolos profile image
Muhammed H. Alkan • Edited

Also, you can use python __setattr__ magic method to control whatever will be run when setting an attribute. That will be helpful when making immutable values.

class Constants:
    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise Exception(f"Cannot change value of {name}.")
        self.__dict__[name] = value

a = Constants()

a.b = 2

print(a.b)

a.b = 1

print(a.b)

The output will be

2
Traceback (most recent call last):
  File "python.py", line 13, in <module>
    a.b = 1
  File "python.py", line 4, in __setattr__
    raise Exception(f"Cannot change value of {name}.")
Exception: Cannot change value of b.

But technically it will still be mutable because

a.__dict__["b"] = 1

Python magic methods are really cool, whoever doesn't know about Python's magic methods should read rszalski.github.io/magicmethods/

Thanks for your beautiful post!