slots in python

In this tutorial, we will try to understand slots in Python with a simple example.

In Python, we use __dict__ function to store the object attributes. This allows setting new attributes at runtime.
The function __dict__ acts as a dictionary. It doesn’t have a fixed number of attributes stored. One can add attributes to the dictionary after defining them but dynamic adding of attributes to a class is not possible in built-in classes like ‘int’ or ‘list’ etc.

a=59
a.b="Dynamic allocation?"
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a.b="Dynamic allocation?"
AttributeError: 'int' object has no attribute 'b'
 >>> class myClass(object):
     def __init__(self, *args, **kwargs):
            self.x = 1
             self.y = 2

>>> instance = myClass()
>>> instance.__dict__
>>> from sys import getsizeof
>>> getsizeof(myClass())
{'y': 2, 'x': 1}
32

However the above function takes up lesser spaces but also, this leads to the function taking up a lot of space in RAM(if thousands and millions of objects are there).
To solve this limitation, we have __slots__ in Python. It provides a static structure not allowing adding attributes after the creation of an instance. __slots__ saved about 9GB RAM.
To define __slots__, one has to define a list with the name ___slots__ which would contain all the attributes to be in use.

Let’s learn slots in Python with a simple piece code.

__slots__ in Python

class Ria_Class(object):
...     __slots__ = ('x', 'y') 
...     def __init__(self, *args, **kwargs):
...         self.x = 1
...         self.y = 2

>>> G=Ria_Class()
>>> G.__slots__
>>> G.x
>>> G.y

1
2

NOTE: ONE SHOULD DECLARE A PARTICULAR SLOT ONE TIME IN A CLASS. AN ERROR WON’T OCCUR IF THIS IS NOT FOLLOWED BUT OBJECTS WILL TAKE UP MORE SPACE THAN THEY SHOULD

class Black:
  __slots__=['foo', 'blah']
class Right (Black):
  __slots__=['babaaa']
class Left(Black):
  __slots__=['foo','blah','babaaa']
 
from sys import getsizeof
getsizeof (Right()),getsizeof(Left())

(36,44)



In the above program, __slots__ is used in the class Right only once declaring a particular slot one time in the class. While the opposite happened in class Left thus declaring three slots at one time. Thus the size of the class Right is 36 which is lesser than 44 (size of class Left).

In the above programs, the line “__slots__= ……..” is to define the slots and “def __init__” we define or instantiate the values.

Also lastly, __slots___ was actually created for faster attribute access.

Leave a Reply

Your email address will not be published. Required fields are marked *