Back
+20 XP
Concept

Custom Abstract Base Classes & Dynamic Registration

`abc.ABCMeta` enforces contract interfaces across classes. Beyond mandatory `@abstractmethod` definitions, `ABCMeta.register()` supports virtual subclassing: allowing third-party classes to satisfy `isinstance(obj, MyInterface)` without explicit inheritance 🎭🛡️.

python
import abc

class DataSink(abc.ABC):
    @abc.abstractmethod
    def write_batch(self, batch):
        pass

# External third-party class that does not inherit from DataSink:
class CustomFileWriter:
    def write_batch(self, batch):
        return len(batch)

# Dynamically register as a virtual subclass:
DataSink.register(CustomFileWriter)

writer = CustomFileWriter()
print(f"Is virtual subclass instance? {isinstance(writer, DataSink)} 🚀")

# 88. Custom Abstract Base Classes & Dynamic Registration If you require an object to adhere to an interface in Java or C++, that object must explicitly `implements` your interface. If a third-party library authored a class that has all the exact right methods, you have to write an adapter wrapper. Python's `ABCMeta` solves this elegantly 🛑. ```python # The Traditional Inheritance Trap: # Class Must Inherit From Interface -> Tight Coupling! # Python Virtual Subclassing (Duck Typing with Type Safety): # Interface.register(ThirdPartyClass) # isinstance(third_party_obj, Interface) -> TRUE! ``` ### How ABC Registration Works 1. **`__subclasscheck__()`**: When `issubclass(Candidate, MyABC)` is evaluated, `ABCMeta` checks its internal weak-reference set of registered classes. If `Candidate` (or any of its base classes) was registered, it returns `True`. 2. **`__instancecheck__()`**: `isinstance(obj, MyABC)` delegates directly to `__subclasscheck__(type(obj))`. 3. **Structural Subtyping (`__subclasshook__`)**: You can even implement `__subclasshook__(cls)` on your ABC to dynamically inspect if a candidate class possesses specific method names, achieving compile-free structural typing (like Go interfaces) 🎭🛡️. --- ### Interactive Pop-Quiz 🧠 #### What does calling MyABC.register(ThirdPartyClass) accomplish in Python's object model? - [ ] It registers ThirdPartyClass as a virtual subclass, making isinstance() return True without modifying its class inheritance tree 🎭 - [ ] It copies all methods of MyABC into ThirdPartyClass at runtime - [ ] It forces ThirdPartyClass to recompile its bytecode with C extensions - [ ] It disables garbage collection for all instances of ThirdPartyClass --- ### Practical Challenge 🎯 Define an `abc.ABC` interface `Codec` with abstract method `encode(data)`. Create an independent class `JsonCodec` implementing `encode(data)` returning `'JSON'`. Register `JsonCodec` as a virtual subclass of `Codec`. Assert `issubclass(JsonCodec, Codec)` is `True` and `isinstance(JsonCodec(), Codec)` is `True`. Print `'VIRTUAL_SUBCLASS_VERIFIED'`. <details> <summary>Solution</summary> ```python import abc class Codec(abc.ABC): @abc.abstractmethod def encode(self, data): pass class JsonCodec: def encode(self, data): return "JSON" Codec.register(JsonCodec) codec = JsonCodec() assert issubclass(JsonCodec, Codec) is True assert isinstance(codec, Codec) is True print("VIRTUAL_SUBCLASS_VERIFIED") ``` </details>

Checkpoint

What does calling `MyABC.register(ThirdPartyClass)` accomplish in Python's object model? 🧠

Practice

Define an `abc.ABC` interface `Codec` with abstract method `encode(data)`. Create an independent class `JsonCodec` implementing `encode(data)` returning `'JSON'`. Register `JsonCodec` as a virtual subclass of `Codec`. Assert `issubclass(JsonCodec, Codec)` is `True` and `isinstance(JsonCodec(), Codec)` is `True`. Print `'VIRTUAL_SUBCLASS_VERIFIED'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks