historic = true
可以实现一个callback 函数
def callback(result):
print("llll", result)
pm = pluggy.PluginManager("myproject")
pm.add_hookspecs(MySpec)
# register plugins
pm.hook.myhook.call_historic(kwargs={"arg1": 10, "arg2": 30}, result_callback=callback)
pm.register(Plugin_1())
设置historic为true时,需要调用call_historic,通过dict传入hook参数,
如果需要处理hook返回值,需要传入result_callback, 回调函数
function = func
通过直接传入func,来设置func attributes,如果为None,则返回一个包装器setattr_hookspec_opts
通过@hookspec方式包装一个func,设置attributes,
set attributes 之后的func 可以在py模块和class类中识别到,
通过PluginManager.add_hookspecs 传入py或者class
hookspec = pluggy.HookspecMarker("myproject")
class MySpec:
"""A hook specification namespace."""
@hookspec()
def myhook(self, arg1, arg2):
"""My special little hook that you can customize."""
def myhook1(self, arg1, arg2):
"""My special little hook that you can customize."""
myhook1 = hookspec(function=myhook1)
pm = pluggy.PluginManager("myproject")
pm.add_hookspecs(MySpec)
pm.hook.myhook(arg1=1, arg2=2)
pm.hook.myhook1(arg1=1, arg2=2)
firstresult = True
注册hook是1:N方式注册的,即一个hookspec 钩子规范,N个钩子函数实现,
如果firstresult=True,则在第一个不返回None的钩子调用时,结束改hook的调用,
即第 I 个hook是不返回None的,则在第 I 之后停止,调用hook数量是I <= N
class MySpec:
"""A hook specification namespace."""
@hookspec(firstresult=True)
def myhook(self, arg1, arg2):
"""My special little hook that you can customize."""
# myhook = hookspec(historic=True)(myhook)
class Plugin_1:
"""A hook implementation namespace."""
@hookimpl
def myhook(self, arg1, arg2):
print("inside Plugin_1.myhook()")
class Plugin_2:
"""A 2nd hook implementation namespace."""
@hookimpl
def myhook(self, arg1, arg2):
print("inside Plugin_2.myhook()")
return arg1 - arg2
class Plugin_3:
"""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_3())
pm.register(Plugin_2())
pm.register(Plugin_1())
results = pm.hook.myhook(arg1=1, arg2=2)
print(results) # -1, Plugin_3的hook不会调用