Open In App

Python | Use of __slots__

Improve
Improve
Like Article
Like
Save
Share
Report

When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary. In case if we need to allocate thousands of objects, it will take a lot of memory space.
slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.

Example of python object without slots :




class GFG(object):
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2
  
if __name__ == "__main__":
     instance = GFG()
     print(instance.__dict__)


Output :

{'a': 1, 'b': 2}

As every object in Python contains a dynamic dictionary that allows adding attributes. For every instance object, we will have an instance of a dictionary that consumes more space and wastes a lot of RAM. In Python, there is no default functionality to allocate a static amount of memory while creating the object to store all its attributes.
Usage of __slots__ reduce the wastage of space and speed up the program by allocating space for a fixed amount of attributes.

Example of python object with slots :




class GFG(object):
      __slots__=['a', 'b']
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2
  
if __name__ == "__main__":
     instance = GFG()
     print(instance.__slots__)


Output :

['a', 'b']

Example of python if we use dict :




class GFG(object):
      __slots__=['a', 'b']
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2
  
if __name__ == "__main__":
     instance = GFG()
     print(instance.__dict__)


Output :

AttributeError: 'GFG' object has no attribute '__dict__'

This error will be caused.

Result of using __slots__:

  1. Fast access to attributes
  2. Saves memory space


Last Updated : 27 Dec, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads