I was wondering how I can provide an API for my Python program to enable others to extend it with plugins.
I thought about something like from myProgram.plugins import aClassToExtendByOthers, registerThatClass
.
But I have no idea how to provide this.
I could use an exec statement within my loadPlugins
function for every plugin in the plugins-folder, but this would not enable importing stuff I would like to
provide for people to write those plugins.
For a system that I use in several of my programs, I define a directory of plugins, and provide a base plugin class for all plugins to subclass. I then import all modules in the directory, and selectively initialize (by checking to see if they subclass my base plugin class), and store instances of plugins in a dictionary (or list). I have found that the command dispatch pattern has worked effectively for me as a way to structure the plugins and pass events. The base plugin (or another optional interface class) can provide the methods that the plugin needs to interact with the application. I hope this helps. It may not be the best way to do it, but it has worked for me.
In addition, you could do additional filtering, such as requiring plugin files to have a prefix (e.g. __plug_file.py__
and __plug_other.py__
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With