pythoninheritancelowest-common-ancestor

How to determine the closest common ancestor class


Suppose I have four classes: A, B derived from A, C derived from A, and D derived from C. (So I always have single inheritance.) In python, what is the best way to determine the closest common ancestor of any two (instances of such) classes? Specifically, I need a function clcoancl(X,Y) for which clcoancl(A, B) == A, clcoancl(B, C) == A, and clcoancl(C, D) == C.


Solution

  • This should work for single or multiple inheritance, with any number of classes as input:

    import inspect
    from collections import defaultdict
    
    def clcoancl(*cls_list):
        mros = [list(inspect.getmro(cls)) for cls in cls_list]
        track = defaultdict(int)
        while mros:
            for mro in mros:
                cur = mro.pop(0)
                track[cur] += 1
                if track[cur] == len(cls_list):
                    return cur
                if len(mro) == 0:
                    mros.remove(mro)
        return None # or raise, if that's more appropriate
    

    As both NPE and Daniel Rossman have mentioned though, this is probably not the optimal solution to your root problem.