Sub topic 10
Virtual subclasses with register
This chapter assumes you can define an ABC with @abstractmethod and that you know what isinstance and issubclass return for ordinary inheritance. An ABC normally gets its subclasses through inheritance. register is the second way: you declare that an existing class counts as a subclass without changing its bases. The result is called a virtual subclass.
What register does
ABC.register(cls) adds cls to a registry kept by the ABC's metaclass, ABCMeta. After that, issubclass(cls, ABC) and isinstance(obj, ABC) return True for cls and its instances.
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
class LegacyFile:
def close(self) -> None:
print("closed")
Closeable.register(LegacyFile)
print(isinstance(LegacyFile(), Closeable))
print(issubclass(LegacyFile, Closeable))
print(Closeable in LegacyFile.__mro__)The first two lines print True. The third prints False. LegacyFile still inherits only from object. The registry changes how isinstance and issubclass answer. It does not change the class.
Why you would register a class
Registration is for classes you cannot, or should not, edit.
- Third-party or legacy code. You can't add
Closeableto the bases of a class in a library you don't own. - Built-in types. The standard library does this itself:
tuple,strandrangeare registered ascollections.abc.Sequence, anddictis registered asMutableMapping. - Avoiding imports. Your ABC module can stay free of imports from the module that defines the concrete class. The concrete module, or a third module, performs the registration.
Registering with a decorator
register returns the class it was given. This means it works as a class decorator, which keeps the registration next to the class definition.
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
def close_quietly(self) -> None:
try:
self.close()
except Exception:
pass
@Closeable.register
class LegacyFile:
def close(self) -> None:
print("closed")
class TempFile(LegacyFile):
pass
print(isinstance(TempFile(), Closeable))
print(hasattr(LegacyFile(), "close_quietly"))This prints True, then False. Two facts follow from it:
- Subclasses of a registered class are virtual subclasses too.
TempFilewas never registered, but it inherits fromLegacyFile, soisinstance(TempFile(), Closeable)isTrue. - Registration inherits nothing.
LegacyFilegets noclose_quietly, because the ABC is not in its MRO (method resolution order). Mixin methods and default implementations on the ABC are unavailable to virtual subclasses.
Nothing is verified
When a real subclass leaves an abstract method unimplemented, ABCMeta blocks instantiation. A registered class is never checked this way. Python trusts the claim.
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
@Closeable.register
class Forgetful:
pass
obj = Forgetful()
print(isinstance(obj, Closeable))
try:
obj.close()
except AttributeError as exc:
print("AttributeError:", exc)The isinstance call prints True, and then the close call fails with AttributeError. The registration is a promise by the programmer. If it is false, you find out when the missing method is called, not at registration or instantiation.
How the check is answered
issubclass(C, Abc) goes through ABCMeta.__subclasscheck__. The order of the steps explains the behavior above.
The registry lookup is itself a recursive issubclass call, which is why the subclasses of a registered class also match. The ABC's subclasses are searched as well, so registering on a child ABC makes the class a virtual subclass of the parent ABC too.
from abc import ABC
class Reader(ABC):
pass
class BufferedReader(Reader):
pass
class Socket:
pass
BufferedReader.register(Socket)
print(issubclass(Socket, BufferedReader))
print(issubclass(Socket, Reader))Both lines print True. A buffered reader is a reader, so a virtual buffered reader is a virtual reader.
The results are cached for speed, both positive and negative. Calling register invalidates the caches, so a result computed before the registration doesn't go stale.
Edge cases
| Situation | Result |
|---|---|
| Registering the same class twice | Harmless. The second call returns the class unchanged. |
| Registering a class that already inherits from the ABC | Harmless. It is already a subclass, so nothing is added. |
| Registering a class that is an ancestor of the ABC | `RuntimeError`: "Refusing to create an inheritance cycle". |
| Registering something that is not a class | `TypeError`: "Can only register classes". |
| Registering a class with no matching methods | Accepted silently. Calls fail later with `AttributeError`. |
The cycle case is easy to reproduce:
from abc import ABC
class Base(ABC):
pass
class Child(Base):
pass
Base.register(Child)
try:
Child.register(Base)
except RuntimeError as exc:
print("RuntimeError:", exc)Base.register(Child) is allowed and does nothing, because Child already inherits from Base. Child.register(Base) would make Base a subclass of its own subclass, so Python refuses.
Pitfalls specific to registration
- Registration must run before the check. The registry is built at runtime. If the module that calls
registeris never imported,isinstancereturnsFalse. Put registrations in a module that is always imported with the ABC, or in the module defining the concrete class. - Static type checkers do not follow it. Tools such as mypy and pyright analyze the source and generally don't treat a registered class as a subclass. Code that passes
LegacyFilewhere aCloseableis expected can be flagged even though the runtime check passes. If static checking matters, considertyping.Protocol(covered in a later chapter). - No inherited behavior. Don't put logic you need in the ABC's concrete methods and then register classes against it. Virtual subclasses won't have those methods.
- The registry holds the class. The registration is global for the process and cannot be removed through a public API. In tests, register helper classes defined for that test only, so the registry doesn't accumulate unrelated entries.
Choosing between inheriting and registering
Prefer inheritance when you own the class. It checks abstract methods at instantiation, passes mixin methods down, and makes the relationship visible in the source and to type checkers. Use register when you can't change the class or when importing the ABC into the class's module would create a dependency problem. If you want any class with the right methods to qualify without even calling register, the next chapter covers __subclasshook__.
Exercise
Given class Stream(ABC) with an abstract read method and a concrete read_all method that calls read in a loop, and class Pipe: def read(self): return b"" registered with Stream.register(Pipe), what do isinstance(Pipe(), Stream) and hasattr(Pipe(), "read_all") return, and why?
Show answer
isinstance(Pipe(), Stream) returns True because Pipe is in Stream's registry. hasattr(Pipe(), "read_all") returns False because registration does not add Stream to Pipe's MRO, so Pipe inherits none of Stream's concrete methods. To get read_all, Pipe would have to inherit from Stream.
Exercise
A teammate registers a class that has no close method as a virtual subclass of Closeable. When does Python report the problem, and what error appears?
Show answer
Python does not report it at registration or at isinstance time, because register performs no checks on the methods. The failure appears only when code calls obj.close(), as an AttributeError.