Skip to content
Advertisement

Are there disadvantages of using __slots__?

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.

JavaScript

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__.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement