Reputation: 3832
Is using slots in python a good pythonic technique or it is a habit coming from the C family of languages? I heard that they enhance performance of the program and reduce memory consumption, espessially when many objects are created. In principle, using slots may become a daily routine because almost always one may know what attributes of the class will be. So should I use slots all the times? When should I use slots exactly?
Upvotes: 4
Views: 2440
Reputation: 19209
Here is the 'official' answer "slots A declaration inside a class that saves memory by pre-declaring space for instance attributes and eliminating instance dictionaries. Though popular, the technique is somewhat tricky to get right and is best reserved for rare cases where there are large numbers of instances in a memory-critical application."
I believe that changes to the CPython dict internals in 3.6 reduced the gain from __slots__
a bit.
Upvotes: 3