What is __slots__ and when is it useful?

Normally, all class objects have an __dict__ which allows new attributes to be bound to a class instance at runtime. When a class is defined with __slots__, only attributes whose names are present in the __slots__ sequence are allowed. This results in instances of this class not having an __dict__ attribute and not being able to bind new attributes at run time.

__slots__ is useful because it eliminates the memory overhead of a python dictionary, while still allowing you to use a structured class. When dealing with a large number of class objects, the memory savings can be quite dramatic.

 

This Question is not yet answered!

 
 

Related Open Questions