Hi Pythonistas!
Today we are learning an advanced technique in python which is “use __slots__ to make class efficient”. We know that we change the number of attributes dynamically. See the example
class Dynamic:
def __init__(self, a, b):
self.a = a
self.b = b
In [15]: a = Dynamic(1, 2)
In [16]: a.a
Out[16]: 1
In [17]: a.b
Out[17]: 2
In [18]: a.c = 100
In [19]: a.c
Out[19]: 100
In [20]: a.__dict__
Out[20]: {'a': 1, 'b': 2, 'c': 100}
In [21]:
We can see that a and b are the attributes of the class but we have added another attribute c at time time. Python did this using a dictionary. Under the hood python class is a dictionary we can use that uses __dict__. This is very useful in many cases but the issue is that the dictionary takes more memory. In certain cases the attributes are fixed with no need for this dynamic capability or no need for mutation at time time we can use the power of __slots__. Using slots we can make class immutable and also more memory efficient. Let us check with an example
class FixedClass:
__slots__ = ('a', 'b')
def __init__(self, a, b):
self.a = a
self.b = b
In [29]: b = FixedClass(1, 2)
In [30]: b.a
Out[30]: 1
In [31]: b.b
Out[31]: 2
In [32]: b.c = 10
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[32], line 1
----> 1 b.c = 10
AttributeError: 'FixedClass' object has no attribute 'c'
In [33]: b.__dict__
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[33], line 1
----> 1 b.__dict__
AttributeError: 'FixedClass' object has no attribute '__dict__'
In [34]: b.__slots__
Out[34]: ('a', 'b')
In [35]:
Here in this FixedClass we have specified a and b in slots so if we try to mutate the class it will throw an AttributeError. Same for __dict__ also.
When to use slots
- You have a large number of instances of a class.
- Memory usage is a critical factor.
- You want to enforce a fixed set of attributes for instances.
I hope you have learned new concepts from this post. Please share your valuable suggestions with afsal@parseltongue.co.in