0

I'm using this line to get all classes used in a script:

clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)

Is there a (common) way to filter out all classes but those which were created within the script? (I don't want the names of the classes which were imported.)

Simply looping over all elements and checking for __main__ is imho too ugly.

1 Answer 1

1

You inspect the __module__ attribute of those classes:

clsmembers = [c for c in inspect.getmembers(sys.modules[__name__], inspect.isclass) if c[1].__module__ == __name__]

Demo:

>>> import inspect
>>> import sys
>>> class Foo(object): pass
... 
>>> from json import *
>>> inspect.getmembers(sys.modules[__name__], inspect.isclass)
[('Foo', <class '__main__.Foo'>), ('JSONDecoder', <class 'json.decoder.JSONDecoder'>), ('JSONEncoder', <class 'json.encoder.JSONEncoder'>)]
>>> [c for c in inspect.getmembers(sys.modules[__name__], inspect.isclass) if c[1].__module__ == __name__]
[('Foo', <class '__main__.Foo'>)]
Sign up to request clarification or add additional context in comments.

Comments

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.