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.
Wonderful ideas! You are providing the different kinds of content is very useful for me and I gain more details from your article. I am always following your blog and keep posting...
ReplyDeleteSpark Training in Chennai
Spark Training
Excel Training in Chennai
Corporate Training in Chennai
Embedded System Course Chennai
Linux Training in Chennai
Tableau Training in Chennai
Power BI Training in Chennai
Social Media Marketing Courses in Chennai
ReplyDeleteGreat info. The content you wrote is very interesting to read. This will loved by all age groups.
ReactJS Training in Chennai
ReactJS Training
ReactJS course
ccna Training in Chennai
Salesforce Training in Chennai
Angularjs Training in Chennai
Nice post. I learned some new information. Thanks for sharing.
ReplyDeletezhosters
Guest posting sites
I am very proud to read such an informative blog. i Will follow your updates in future so, please add more and more ideas.
ReplyDeletePython Training in Chennai
Python Training Institute in Chennai
JAVA Training in Chennai
Big data training in chennai
Selenium Training in Chennai
IOS Training in Chennai
Python Training in Chennai
Python Course in Chennai
Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
ReplyDeleteCyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course
smm panel
ReplyDeleteSmm panel
iş ilanları
instagram takipçi satın al
https://www.hirdavatciburada.com/
beyazesyateknikservisi.com.tr
SERVİS
tiktok jeton hilesi
maltepe samsung klima servisi
ReplyDeletependik arçelik klima servisi
tuzla samsung klima servisi
kadıköy samsung klima servisi
maltepe mitsubishi klima servisi
kadıköy mitsubishi klima servisi
kartal vestel klima servisi
ümraniye vestel klima servisi
kartal bosch klima servisi
EasyUEFI Enterprise 4.9.2.0 Crack is used for creating, deleting, modifying, configuring, and repairing EFI / UEFI startup options.Easyuefi Crack
ReplyDeleteHappy 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
ReplyDeleteThe 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.
ReplyDeleteGood content. You write beautiful things.
ReplyDeletesportsbet
mrbahis
hacklink
hacklink
korsan taksi
sportsbet
taksi
vbet
vbet
Success Write content success. Thanks.
ReplyDeletekıbrıs bahis siteleri
kralbet
betturkey
betpark
canlı slot siteleri
canlı poker siteleri
deneme bonusu
This post is on your page i will follow your new content.
ReplyDeletecasino siteleri
sportsbet
casino siteleri
sportsbet
mrbahis giriş
mrbahis.co
betgaranti.online
mrbahis
sportsbetgiris.net
dijital kartvizit
ReplyDeletereferans kimliği nedir
binance referans kodu
referans kimliği nedir
bitcoin nasıl alınır
resimli magnet
D0A
beşiktaş
ReplyDeleteeyüpsultan
gebze
marmaris
tekirdağ
VAXC2
https://saglamproxy.com
ReplyDeletemetin2 proxy
proxy satın al
knight online proxy
mobil proxy satın al
GLX
Nice blog.Keep up with your good work.
ReplyDeletePython classes in Pune
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