Best practices for dynamically loading plugins at startup

Jeff Schwab jeffrey.schwab at rcn.com
Tue Sep 27 00:20:06 EDT 2005


Christoph Haas wrote:
> On Sun, Sep 25, 2005 at 11:33:03PM -0400, Jeff Schwab wrote:
> 
>>I recently came up against this exact problem.  My preference is to have 
>>the plugin writer call a method to register the plugins, as this allows 
>>him the most control.  Something along these lines:
>>
>>	class A_plugin(Plugin):
>>		...
>>
>>	class Another_plugin(Plugin):
>>		...
>>
>>	register( A_plugin )
>>	register( Another_plugin, optional_custom_registration_parameters )
> 
> 
> I like the idea. And "supybot" seems to do just that. What would the
> "def register:" do? Maintain a global list of registered plugins?
> I didn't like the idea of having global variables. Or would register
> be a method of some "main" class? How would I access that?

The registry clearly has to be shared between modules, so I think it's 
best to make it a module-level variable.  In the simple-minded code 
below, I've stored it in the "plugins" module.  A better choice might be 
the module that defines your plugins' common base class, if they have one.


# BEGIN framework.py
if __name__ == "__main__":
	import plugins
	print plugins.plugin_registry
# END framework.py

# BEGIN plugins.py
# Define some plugins.

class A_plugin(object):
	def __init__(self):
		print "A_plugin()"

class Another_plugin(object):
	def __init__(self):
		print "Another_plugin()"

# Register the plugins.

import registry

plugin_registry = registry.Registry()
plugin_registry.register(A_plugin)
plugin_registry.register(Another_plugin)
# END plugins.py

# BEGIN registry.py
class Registry(object):
	"Each instance may be used to store a set of objects."

	def __init__(self):
		"Initialize an empty registry."
		self.registered_objects = set()

	def register(self, o):
		"Add an object to the registry."
		self.registered_objects.add(o)

	def __repr__(self):
		return "Registry Contents:\n\t" + \
		"\n\t".join(repr(o) for o in self.registered_objects)
# END registry.py



More information about the Python-list mailing list