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?
Asked
Active
Viewed 2,088 times
3
-
3Only use slots if you think you need to create lots and lots (read 100,000s) of such objects. Otherwise, it seems totally unecessary. – juanpa.arrivillaga Apr 19 '17 at 20:54
-
1Pretty comprehensive answer to this here http://stackoverflow.com/a/28059785/532978 – JCOC611 Apr 19 '17 at 20:56
-
1If you're wondering whether or not you should use slots, don't use slots. If you really need it, you'll know. – wim Apr 19 '17 at 20:56
-
There are secondary benefits - you can add a `__slots__` `dict` to document your code, and linters/IDEs such as *PyCharm* use `__slots__` to check your variable access. – c z Oct 02 '19 at 07:19
1 Answers
3
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.

Terry Jan Reedy
- 18,414
- 3
- 40
- 52
-
Yes, the gain has been reduced. Quoting from the book "Learning Python": "In Python 3.3, non-slots attribute space requirements have been reduced with a key-sharing dictionary model, where the __dict__ dictionaries used for objects’ attributes may share part of their internal storage, including that of their keys. This may lessen some of the value of __slots__ as an optimization tool; " – MattSt Aug 28 '22 at 13:57