Thursday, 7 July 2022

How can I discover classes in a specific package in python?

I have a package of plug-in style modules. It looks like this:

/Plugins 
/Plugins/__init__.py
/Plugins/Plugin1.py
/Plugins/Plugin2.py 
etc...

Each .py file contains a class that derives from PluginBaseClass. So I need to list every module in the Plugins package and then search for any classes that implement PluginBaseClass. Ideally I want to be able to do something like this:

for klass in iter_plugins(project.Plugins):
    action = klass()
    action.run()

I have seen some other answers out there, but my situation is different. I have an actual import to the base package (ie: import project.Plugins) and I need to find the classes after discovering the modules.



from How can I discover classes in a specific package in python?

No comments:

Post a Comment