Search code examples
pythonweak-referencesslots

Why is __weakref__ removed by default when __slots__ is used?


I think the main purpose of __slots__ is to save the memory usage by allowing to specify properties explicitly, instead of using __dict__ allowing dynamic property assignment on the instances. So I somehow understand why __dict__ is removed by default when using __slots__. But why does it meanwhile remove __weakref__ by default?

Reference: https://docs.python.org/3/reference/datamodel.html#slots


Solution

  • I can't read minds, but I suspect the rationale goes like this:

    1. If __weakref__ wasn't disabled by default when using __slots__, providing a way to save the associated memory explicitly would require yet another special opt-out mechanism
    2. More special cases add complexity to the language, and this one would provide no real benefit

    Given how infrequently weak references are used at all, it was probably deemed simpler to simply have it disabled by default, with the option to opt back in.

    Diving to implementation details, in a sense, unslotted user-defined classes have precisely two "slots" (one for __dict__, one for __weakref__) over and above the base object header, so having __slots__ say "Replace the default with this explicit list" makes it natural to remove both __dict__ and __weakref__ when __slots__ comes into play.