pluggy python 最小产品级插件框架

pluggy python 最小产品级插件框架,目前在pytest,tox 以及devpi 项目中都有使用到

简单使用

  • 项目准备
  poetry new plugindemo
poetry shell
poetry add pluggy
  • 代码
    plugindemo/demo.py
import pluggy
 
hookspec = pluggy.HookspecMarker("myproject")
hookimpl = pluggy.HookimplMarker("myproject")
 
 
class MySpec:
    """A hook specification namespace."""
 
    @hookspec
    def myhook(self, arg1, arg2):
        """My special little hook that you can customize."""
 
 
class Plugin_1:
    """A hook implementation namespace."""
 
    @hookimpl
    def myhook(self, arg1, arg2):
        print("inside Plugin_1.myhook()")
        return arg1 + arg2
 
 
class Plugin_2:
    """A 2nd hook implementation namespace."""
 
    @hookimpl
    def myhook(self, arg1, arg2):
        print("inside Plugin_2.myhook()")
        return arg1 - arg2
 
 
# create a manager and add the spec
pm = pluggy.PluginManager("myproject")
pm.add_hookspecs(MySpec)
 
# register plugins
pm.register(Plugin_1())
pm.register(Plugin_2())
 
# call our ``myhook`` hook
results = pm.hook.myhook(arg1=1, arg2=2)
print(results)
  • 运行效果

说明

也有一个pluginbase的开源项目,但是目前缺少维护了,python 进行插件化系统开发还是比较简单的,而且方法也很多,比如importlib 动态创建模块就是一个比较常见的用法,dbt adapter 就使用到了此方法

参考资料

https://github.com/pytest-dev/pluggy
https://pluggy.readthedocs.io/en/latest/
https://github.com/mitsuhiko/pluginbase

posted on 2024-04-07 08:00  荣锋亮  阅读(24)  评论(0编辑  收藏  举报

导航