Search code examples
pythonsuperclass

Greatest Common Superclass


Is there any simple way to get the "greatest common superclass" of a list of objects? For example, if

class A(object): pass
class B(A): pass
class C(A): pass
class D(B, C): pass
class E(C): pass
class F(D, E): pass

and

b = B()
d = D()
e = E()

then

gcs(b, e) is A
gcs(d, e) is C
gcs(e, e) is E

Solution

  • Based on Martijn's idea, but using an easier approach considering that time complexity is not going to be an issue here(Thanks to @veedrac for his inputs):

    def gcs(*instances):
        classes = [type(x).mro() for x in instances]
        for x in classes[0]:
            if all(x in mro for mro in classes):
                return x
    
    print gcs(b, e)
    print gcs(d, e)
    print gcs(e, e)
    

    Output:

    <class '__main__.A'>
    <class '__main__.C'>
    <class '__main__.E'>
    

    A slight variant of the above code using sets:

    def gcs(*instances):
        mros = (type(ins).mro() for ins in instances)
        mro = next(mros)
        common = set(mro).intersection(*mros)
        return next((x for x in mro if x in common), None)