Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use slots in python?

Tags:

python

slots

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?

like image 427
freude Avatar asked Sep 13 '25 10:09

freude


1 Answers

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.

like image 185
Terry Jan Reedy Avatar answered Sep 15 '25 02:09

Terry Jan Reedy