Search code examples
pythoninspection

In Python, how do I get the list of classes defined within a particular file?


If a file myfile.py contains:

class A(object):
  # Some implementation

class B (object):
  # Some implementation

How can I define a method so that, given myfile.py, it returns [A, B]?

Here, the returned values for A and B can be either the name of the classes or the type of the classes.

(i.e. type(A) = type(str) or type(A) = type(type))


Solution

  • You can get both:

    import importlib, inspect
    for name, cls in inspect.getmembers(importlib.import_module("myfile"), inspect.isclass):
    

    you may additionally want to check:

    if cls.__module__ == 'myfile'