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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With