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   荣锋亮  阅读(63)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2023-04-07 asciinema 方便的终端录屏方案
2021-04-07 npm的package.json中的dependencies版本号
2021-04-07 开发一个materialize cube.js driver
2020-04-07 minio 关闭默认browser
2020-04-07 s3-fuse docker运行试用
2020-04-07 minio lifecycle 配置
2019-04-07 WRITING POSTGRESQL TRIGGERS IN GO

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示