Задать вопрос

Тел: +7 965 3737 888

429

Просмотров

5

Ответов

Plugin Framework

<p>This is a very basic -- yet fully functional -- framework for producing a loosely coupled plugin architecture. Full details of its use can be found <a href="http://gulopine.gamemusic.org/2008/jan/10/simple-plugin-framework/">on my blog</a>, but the basics are listed below.</p>
<h2>Defining a mount point for plugins</h2>
class ActionProvider:
    __metaclass__ = PluginMount

<h2>Implementing plugins</h2>
class Insert(ActionProvider):
    def perform(self):
        # Do stuff here

class Update(ActionProvider):
    def perform(self):
        # Do stuff here

<h2>Utilizing plugins</h2>
for action in ActionProvider.plugins:
    action.perform()

<p>Yes, it really is that simple.</p>

Вопрос полезен? Да0/Нет0
file_2721.py(682.0б)
None

Ответы (5):

Ответeagleamon:01.08.2012
Ответ полезен? Да0/Нет0

Hi, really nice and neat solution. Just a thing, I don't see a way to do this if your plugins are defined in different module files without having to look for them somewhere. Just an example:

main.py plugins/ metaclass.py plugin.py init.py plugin1.py plugin2.py etc..

and in init.py: all = [p for p in glob.glob(....)...]

which quite destroy the benefit not to look for anything. Am I missing something ?

Thanks for the idea anyway !!

Ответffsffd:27.04.2011
Ответ полезен? Да0/Нет0

Oops, here's the code again, correctly formatted.

if __name__ == '__main__':
    for action in ActionProvider.plugins:
        action().perform()

Ответffsffd:27.04.2011
Ответ полезен? Да0/Нет0

This is a little late, but just informational for everyone else.

The poster above me encountered the error because action (which is a class), is not being instantiated first.

So the fix is: if name == 'main': for action in ActionProvider.plugins: action().perform()

Really simple. :) And this idea really rocks.

Ответmattjvincent:26.08.2010
Ответ полезен? Да0/Нет0

Help...

I received this error:

TypeError: unbound method perform() must be called with Insert instance as first argument (got nothing instead)

Here is the code....

class PluginMount(type):
    def __init__(cls, name, bases, attrs):
        if not hasattr(cls, 'plugins'):
            cls.plugins = []
        else:
            cls.plugins.append(cls)

class ActionProvider(object):
    __metaclass__ = PluginMount

class Insert(ActionProvider):
    def perform(self):
        print 'Insert'

class Update(ActionProvider):
    def perform(self):
        print 'Update'

if __name__ == '__main__':
    for action in ActionProvider.plugins:
        action.perform()

Ответjezdez:22.01.2009
Ответ полезен? Да0/Нет0

This is just unbelievable awesome. Great snippet and weblog post!