79767122

Date: 2025-09-17 09:54:18
Score: 1
Natty:
Report link

Sequence is an ABC and lets you define a virtual subclass. This is a class that implements the full protocol/interface of Sequence without being tied to the class in any technical way: methods don't resolve to the other class.

If class A is a virtual subclass of Base, A is not actually a subclass of Base, but the programmer of A guarantees that it behaves like a subclass.

Why is this necessary?

In the spirit of duck-typing, I should be able to define a class that behaves like another class in any way I want. One problematic difference between such a class and a regular subclass is dynamic type-checking. issubclass(A, Base) and isinstance(A(), Base) will fail even if any A can be used as a Base. This is why explicit type-checking is sometimes considered un-pythonic, it breaks duck-typing.

How is this achieved?

Any ABC has the class method register that lets you specify that an existing class is a virtual subclass of the ABC. Sequence from collections is an ABC.

Example from documentation linked above:

from abc import ABC

class MyABC(ABC):
    pass

MyABC.register(tuple)

assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)

Why not just inherit?

If you want to implement an API of another class, a non-duck-typing language would give you two choices: (1) inherit from it or (2) define a new supertype from which both classes will inherit. There are many scenarios where that would make sense.

(1) will have a memory overhead that is completely unnecessary if you fully implement the interface without relying on the other classes code. 1 (2) requires you to modify the code of the other class, which may not be possible if you don't control that code.

With virtual subclassing you are saying: I define an interface, and I know and guarantee that this other class by someone else implements it.

1 To avoid that overhead you would have to create a weird class that does not call super().__init__(), but then what about __new__? What about C-extensions, __init_subclass__ and other things?

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • RegEx Blacklisted phrase (0.5): Why is this
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • High reputation (-1):
Posted by: julaine