What is use of __slots__?

By default, each python object has a __dict__ atttribute which is a dictionary containing all other attributes. You can imagine using a dictionary to store attribute takes some extra space & time for accessing it. But advantage is you can dynamically add attributes to objects of classes.

When you use __slots__, any object created for that class won’t have a __dict__ attribute. Instead, all attribute access is done directly via pointers. It prevents the dynamic creation of attributes. So object instances has faster attribute access and space savings in memory.

If you are going to use thousands or millions of objects of the same class __slots__ is recommended for good performance.

Leave a Reply

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