Suppose you have a base class A, and this class is reimplemented by B and C.
Suppose also there’s a class method A.derived() that tells you which classes are reimplementing A, hence returns [B, C], and if you later on have class D(A): pass or class D(B): pass, now A.derived() returns [B,C,D].
How would you implement the method A.derived() ? I have the feeling that is not possible unless you use metaclasses. You can traverse the inheritance tree only from child to parent with the standard mechanism. To have the link in the other direction, you have to keep it “by hand”, and this means overriding the traditional class declaration mechanics.
If you define your classes as a new-style class (subclass of
object) then this is possible since the subclasses are saved in__subclasses__.I do not know exactly when this was introduced or if there are any special considerations. It does however work fine to declare a subclass in a function:
However, you need to note that until the class definitions have been run the interpreter does not know about them. In the example above
Cis not recognized as a subclass of A until the functionfis executed. But this is the same for python classes every time anyway, as I presume you are already aware of.