Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate nested classes in python?

How to implement function, which enumerate nested classes?

class A(object):
    class B(object):
        pass

    class C(object):
        pass


def enumerate_nested_classes(_class):
    return ()  # need proper implementation instead


assert set(enumerate_nested_classes(A)) == {A.B, A.C}
like image 414
cridnirk Avatar asked May 29 '26 20:05

cridnirk


1 Answers

inspect.getmembers() in conjunction with inspect.isclass() should help here:

classes = [name for name, member_type in inspect.getmembers(A)
           if inspect.isclass(member_type) and not name.startswith("__")]

print(classes)  # prints ['B', 'C']

Note that not name.startswith("__") check is needed to exclude __class__ - I suspect there is a simpler and a more pythonic way to do so, would appreciate if somebody would point that out.

like image 158
alecxe Avatar answered May 31 '26 09:05

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!