Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide an API to extend a Python program with plugins?

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.

like image 258
Niklas R Avatar asked Nov 04 '22 18:11

Niklas R


1 Answers

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__).

like image 157
Michael Smith Avatar answered Nov 09 '22 12:11

Michael Smith