One use of __slots__ in Python is to disallow new attributes:
class Thing:
__slots__ = 'a', 'b'
thing = Thing()
thing.c = 'hello' # error
However, this doesn’t work if a class inherits from another slotless class:
class Whatever:
pass
class Thing(Whatever):
__slots__ = 'a', 'b'
thing = Thing()
thing.c = 'hello' # ok
That’s because it also inherits the __dict__ from its parent which allows additional attributes.
Is there any way of blocking the __dict__ from being inherited?
It seems to me that this would allow a sub class to be less generic that its parent, so it’s surprising that it doesn’t work this way naturally.
Comment
OK, the question arises as whether this would violate the https://en.wikipedia.org/wiki/Liskov_substitution_principle . This, in turn buys into a bigger discussion on inheritance.
Most books would, for example, suggest that a circle is an ellipse so a Circle class should inherit from an Ellipse class. However, since a circle is more restrictive, this would violate the Liskov Substitution Principle in that a sub class should not do less than the parent class.
In this case, I’m not sure about whether it applies here. Python has no access modifiers, so object data is already over-exposed. Further, without __slots__ Python objects are pretty promiscuous about adding additional attributes, and I’m not sure that’s really part of the intended discussion.