# -*- coding:utf-8 -*-from pluggy import PluginManager, HookspecMarker, HookimplMarker
hookspec = HookspecMarker("myPluggyDemo_4")
hookimpl = HookimplMarker("myPluggyDemo_4")classHookSpec:
@hookspec()defcalculate(self, a, b):passclassHookImpl1:
@hookimpl(tryfirst=True)defcalculate(self, a, b):return a + b
classHookImpl2:
@hookimpl
defcalculate(self, a, b):return a * b
pm = PluginManager("myPluggyDemo_4")
pm.add_hookspecs(HookSpec)
pm.register(HookImpl1())
pm.register(HookImpl2())print(pm.hook.calculate(a=2, b=3))
Output
[5, 6]
trylast以此類推,攜帶者變爲後執行
hookwrapper
我們實現一個特殊的pluginWrapperPlugin
# -*- coding:utf-8 -*-from pluggy import PluginManager, HookspecMarker, HookimplMarker
hookspec = HookspecMarker("myPluggyDemo_5")
hookimpl = HookimplMarker("myPluggyDemo_5")classHookSpec:
@hookspec
defcalculate(self, a, b):passclassHookImpl1:
@hookimpl
defcalculate(self, a, b):print('HookImpl1 execute!')return a + b
classHookImpl2:
@hookimpl(tryfirst=True)defcalculate(self, a, b):print('HookImpl2 execute!')return a * b
classWrapperPluggy:
@hookimpl(hookwrapper=True)defcalculate(self, a, b):print('WrapperPluggy execute!')print("Before yield")
result =yield#此處返回的值爲其他兩個pluggy執行的結果print(f"After yield,result is {result.get_result()}")return a * b +(a + b)
pm = PluginManager("myPluggyDemo_5")
pm.add_hookspecs(HookSpec)
pm.register(HookImpl1())
pm.register(HookImpl2())
pm.register(WrapperPluggy())print(pm.hook.calculate(a=2, b=3))
Output
WrapperPluggy execute!
Before yield
HookImpl2 execute!
HookImpl1 execute!
After yield,result is [6, 5][6, 5]