I need to find the last common ancestor of a group of classes so I can return that type.
Context, I'm doing some rather complex meta-programing involving overloading numpy functionality. (don't ask) I have a variable number of arguments to a function the types of which I have extracted into a set (with some filtering out of irrelevant types) using this information I need to figure out what the furthest down the type tree where all types share the same base type. I have some first pass attempts but I'm getting tripped up by multiple inheritance and the like.
first pass:
def lca_type(types):
if len(types) == 1:
return types.pop()
filtered_types = set()
for type in types:
if not any(issubclass(type, x) for x in types):
filtered_types.add(type)
if len(filtered_types) == 1:
return filtered_types.pop()
# TODO: things get tricky here
consider the following class hierarchy:
class A(object):
pass
class B(A):
pass
class C(A):
pass
class D(A):
pass
class B1(B):
pass
class B2(B):
pass
class BC(C, B1):
pass
class CD(C, D):
pass
class D1(D):
pass
class BD(B, D):
pass
class B1_1(B1):
pass
expected results:
lca_type({A,BD}) == A
lca_type({C}) == C
lca_type({B1,B2}) == B
lca_type({{B1_1, D}) == A
lca_type({CD, BD}) == D
lca_type({B1_1, BC}) == B1