0

I was looking into abstract base classes in python and was looking at the code in abc.py and came across this tiny class:

class ABC(metaclass=ABCMeta):
"""Helper class that provides a standard way to create an ABC using
inheritance.
"""
__slots__ = ()

Metaclasses are inherited. The idea here is that instead of declaring metaclass=ABCMeta explicitly in your class declaration, you could just subclass ABC and inherit the metaclass. The ABC class serves no purpose other than to set its own metaclass to ABCMeta.

So why does it assign an empty tuple to __slots__? What does this accomplish? Aren't the slots already empty if left uninitialized?

  • Welcome to Stack Overflow. `__slots__` causes the class instances to be created differently internally. An empty `__slots__` designation is **not** the same as omitting it. Please see the linked duplicate for general reference. Alternately, [consider](https://meta.stackoverflow.com/questions/261592) doing your own [research](https://duckduckgo.com/?q=python+__slots__). – Karl Knechtel Jul 21 '22 at 23:26
  • 1
    The key detail is somewhat buried in the accepted answer of the duplicate: "To prevent the creation of a __dict__, you must inherit from object and **all classes in the inheritance must declare `__slots__`** and none of them can have a `__dict__` entry." If `ABC` didn't use `__slots__`, you could not effectively add it to any abstract class. – chepner Jul 21 '22 at 23:47
  • Note that metaclases are not inherited, so much as the metaclass is *chosen* from among the metaclasses of all its parents. – chepner Jul 21 '22 at 23:49

0 Answers0