3

The __slots__ attribute for classes was made with Python 2 or earlier, and according to comment for answer to Python __slots__ it appears that Python 3.3 has improved so the advantage on memory size may not be the reason for using __slots__ in for example Python 3.4 programs.

So should I clean up my code and remove the use of __slots__ in classes, or is there still some good reason for using __slots__ even in Python 3.4 programs?

Community
  • 1
  • 1
EquipDev
  • 5,573
  • 10
  • 37
  • 63
  • Why do you use `__slots__` in the first place? Are you experiencing memory issues with your application? What does a memory profiler tell you about your program run with and without `__slots__`? – jfs Jan 30 '15 at 11:33
  • I added `__slots__` up front since it looked like a good idea to declare the used attributes, and thereby also reduce the memory footprint, even through memory is not a concern in my program. However, the use of `__slots__` broke instance compare (`__eq__`) with `__dict__`, and also appears to break `pickle`, so maybe not a good idea to use, unless there is some other good reason. – EquipDev Jan 30 '15 at 11:45
  • 2
    yes. It is not a good idea to use `__slots__` unless you need it (consider it as an optimization hack that works but breaks easily). – jfs Jan 30 '15 at 11:49
  • What do you mean by "it broke instance compare"? – Ethan Furman May 19 '15 at 01:25
  • @EthanFurman: A general equality check can be made using `__dict__`, like shown here [Elegant ways to support equivalence](http://stackoverflow.com/a/390511/2352082), and that breaks if there is no `__dict__` as result of using `__slots__`. – EquipDev May 26 '15 at 04:56

1 Answers1

2

By using __slots__ you are telling Python not to have a __dict__ attribute on your instances. This is to save memory in cases where you may have thousands upon thousands of instances. This is the reason to use them in Python 2, and it is the reason to use them in Python 3.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237