3

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}
2
  • Does it need to be recursive? Commented Dec 24, 2015 at 17:29
  • What are you actually trying to achieve?! Commented Dec 24, 2015 at 17:34

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Output should be [getattr(A, name) for name in classes] though. Also I don't believe this will get further nested ones ..
@wim thanks, yes, this is not recursive at the moment, let's see if the OP would need to go deeper.
2

You can use the next code:

import types


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

    class C(object):
        pass

def enumerate_nested_classes(_class):
    return [getattr(_class, n) for n in dir(_class) if not n.startswith('__')
            and isinstance(getattr(_class, n), (type, types.ClassType))] 

assert enumerate_nested_classes(A) == [A.B, A.C]

And print enumerate_nested_classes(A) prints [<class '__main__.B'>, <class '__main__.C'>]

NB. dir(_class) resulting list is sorted alphabetically, so when using assert enumerate_nested_classes(A) == [A.B, A.C] it is better to use: assert sorted(enumerate_nested_classes(A)) == sorted([A.B, A.C]).

1 Comment

It's so simple and works even without importing inspect. One more variant of this: (n for n in (getattr(_class, n) for n in dir(_class) if not n.startswith('__')) if isinstance(n, (type, types.ClassType)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.