0

I tried to use for loop in a recursive function to find all path that the child class related to its parents.

class A:
    pass
class B(A):
    pass
class C(A):
    pass
class F(A):
    pass
class L(C,B):
    pass
class D(B,F):
    pass
class M(L,D):
    pass


def bases(cls):
    if cls == object:
        return [object]
    
    for Class in cls.__bases__:
        return [cls] + bases(Class)


print(bases(M))
# the output should be this:
# [[M, L, C, A], [M, L, B, A], [M, D, B, A], [M, D, F, A]]

but the output is [M, L, C, A] . keyword Return didn't allow For Loop to do well . then I wrote the code like this:

for Class in cls.__bases__:
    path = [cls] + bases(Class)
return path

and the output would be [M, D, F, A] . I replaced return with yield but it didn't work and I get error:

TypeError: can only concatenate list (not "generator") to list

what can I do to solve this problem???

1
  • Try to checkup the type of each return, it seems that when you are doing the recursion to see which is the generator. And check the call stack Commented Jul 19, 2022 at 2:55

1 Answer 1

1

Try the following implementation using recursion:

class A:
    pass
class B(A):
    pass
class C(A):
    pass
class F(A):
    pass
class L(C,B):
    pass
class D(B,F):
    pass
class M(L,D):
    pass

def bases(cls):
    if cls.__bases__ == (object, ): # if "root"
        return [cls.__name__]
    return [[cls.__name__, *granpas] for base in cls.__bases__ for granpas in bases(base)]

print(bases(M)) # [['M', 'L', 'C', 'A'], ['M', 'L', 'B', 'A'], ['M', 'D', 'B', 'A'], ['M', 'D', 'F', 'A']]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.