Sub topic 10
Virtual subclasses with register
This chapter assumes you know how ABC and @abstractmethod work, and that isinstance and issubclass accept ABCs. It also assumes you are comfortable with decorators.
The problem register solves
Normally a class joins an ABC by inheriting from it. Sometimes you cannot do that. The class may come from a third-party library, or you may not want to change old code. ABC.register(cls) lets you declare the class a virtual subclass of the ABC without touching it.
Registering a class
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
def close_quietly(self) -> None:
try:
self.close()
except Exception:
pass
class LegacyFile:
def close(self) -> None:
print("closed")
Closeable.register(LegacyFile)
f = LegacyFile()
print(isinstance(f, Closeable))
print(issubclass(LegacyFile, Closeable))
print(Closeable in LegacyFile.__mro__)
print(hasattr(f, "close_quietly"))The output is True, True, False, False. The two checks pass, but Closeable is not in the method resolution order (MRO), the list Python searches for attributes. So LegacyFile inherits nothing from Closeable, including the concrete close_quietly method.
Using register as a decorator
register returns the class it receives, so you can use it as a class decorator. The class below defines no close method, but registration still succeeds.
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
@Closeable.register
class NoClose:
pass
print(issubclass(NoClose, Closeable))
print(isinstance(NoClose(), Closeable))Both lines print True.
What register does not do
Registration is a promise from you, and Python does not verify it. This has three consequences.
- No abstract-method check.
NoClose()instantiates normally, becauseNoClosenever inherits the abstract method. Callingcloseon it raisesAttributeError. - No inherited code. Concrete methods and class attributes on the ABC are not available on the registered class.
- No
super()link. The ABC is absent from the MRO, sosuper()calls never reach it.
Registration is also inherited downward. If you register LegacyFile, any subclass of LegacyFile counts as a virtual subclass too.
Common uses
The standard library uses registration for built-in types. For example, tuple, str, and range are registered as collections.abc.Sequence. They are not real subclasses, which is why Sequence in tuple.__mro__ is False.
You can check this yourself:
from collections.abc import Sequence
print(isinstance((1, 2), Sequence))
print(Sequence in tuple.__mro__)The first line prints True and the second prints False.
Registration fits best in these situations:
- Adapting classes from libraries you do not control.
- Declaring that a built-in type satisfies your interface.
- Letting
isinstancedispatch work on classes that cannot share a base.
If you control the class, plain inheritance is better. It gives you the enforcement and the inherited methods.
Common errors
- Expecting a
TypeError. Incomplete registered classes instantiate without complaint. - Relying on mixins. Code that calls
close_quietlyon anyCloseableinstance fails for registered classes. - Registering too early. Register at import time, in the module that defines or adapts the class, so every later
isinstancecheck sees it.
Exercise
You run Closeable.register(LegacyFile), where LegacyFile defines close. Which of these are true: isinstance(LegacyFile(), Closeable), Closeable in LegacyFile.__mro__, and hasattr(LegacyFile(), "close_quietly")? Why?
Show answer
Only the first is true. Registration makes isinstance and issubclass return True, but it does not add the ABC to the MRO. The class therefore inherits none of the ABC's concrete methods, so close_quietly is missing.