I’m using Python 3.7 and Django. I was reading about __slots__
. Evidently, __slots__
can be used to optimize memory allocation for a large number of those objects by listing all the object properties ahead of time.
class MyClass(object): __slots__ = ['name', 'identifier'] def __init__(self, name, identifier): self.name = name self.identifier = identifier self.set_up()
My perhaps obvious question is why wouldn’t we want to do this for all objects? Are there disadvantages for using __slots__
?
Advertisement
Answer
Fluent Python by Luciano Ramalho lists the following caveats
• You must remember to redeclare
__slots__
in each subclass, since the inherited attribute is ignored by the interpreter.• Instances will only be able to have the attributes listed in
__slots__
, unless you include__dict__
in__slots__
— but doing so may negate the memory savings.• Instances cannot be targets of weak references unless you remember to include
__weakref__
in__slots__
.