tamasgal
tamasgal

Reputation: 26259

Get a list of classes, defined within a script

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.

Upvotes: 0

Views: 56

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

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'>)]

Upvotes: 1

Related Questions