Pluggy源码解读----hook函数调用执行过程分析
作者:redrose2100   类别:    日期:2022-12-10 11:32:23    阅读:1197 次   消耗积分:0 分

    首先看一下pluggy应用代码中执行hook函数调用的代码,如下所示,在分析addhookspecs方法的时候,我们曾经分析过,pm有一个属性时hook,而hook实质上是HookRelay类的实例对象,但是_HookRelay类是一个空类,在add_hookspecs中对hook这个对象设置了一个属性,属性名是myhook,而此属性的值是hc,而hc实质上是_HookCaller类的一个实例,换一句话说pm.hook.myhook就是_HookCaller类的一个实例,那么这里将实例当做函数调用,很显然,在python中这种用法实质上是在调用_HookCaller类中的__call魔法函数。

    1. results = pm.hook.myhook(arg1=1, arg2=2)

    进入HookCaller类中,确实可以找到_call魔法函数,代码试下如下,这里可以看到首先是获取firstresult是否设置为True,如果没有设置,则直接将firstresult设置为False,然后就调用_hookexec方法,而在_HookCaller类的初始化函数中,可以看出_hookexec方法就是传递进来的PluginManager类的_inner_hookexec属性,亦即_multicall函数。

    1. def __call__(self, *args, **kwargs):
    2. if args:
    3. raise TypeError("hook calling supports only keyword arguments")
    4. assert not self.is_historic()
    5. # This is written to avoid expensive operations when not needed.
    6. if self.spec:
    7. for argname in self.spec.argnames:
    8. if argname not in kwargs:
    9. notincall = tuple(set(self.spec.argnames) - kwargs.keys())
    10. warnings.warn(
    11. "Argument(s) {} which are declared in the hookspec "
    12. "can not be found in this hook call".format(notincall),
    13. stacklevel=2,
    14. )
    15. break
    16. firstresult = self.spec.opts.get("firstresult")
    17. else:
    18. firstresult = False
    19. return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)

    因此pm.hook.myhook实质上就是调用了_multicall函数,在前面也曾经说过,_multicall函数是整个pluggy模块的调用执行的核心,这里就将详细的介绍此函数的实现,_multicall的函数代码如下,这里首先可以看到在for循环的时候,是将hook_impls使用reverse进行了反转,这就与我们前面分析到的在添加执行函数的时候好像使用了先进后出队列,那么之类可以看到,并没有使用队列的数据结构,而是使用了列表,只是在这里对列表进行了反转,在每个循环中判断hookwrapper的值是否为True,因为如果hookwrapper为True,则表示方法中有yield,此时就需要将yield之后的调用提前存入这里teardowns列表,同时执行所有的函数,此外这里同时可以看到,在判断firstresult,如果firstresult为True,当有一个结果时就会停止执行了,在finally部分可以看到,这里又将teardowns进行反转然后再依次执行,这就做到了当有多个插件类的方法中使用yield时,先注册的插件类中的yield之后的代码是后执行的,而这个功能对于pytest中的teardown就很有用处。

    1. def _multicall(hook_name, hook_impls, caller_kwargs, firstresult):
    2. """Execute a call into multiple python functions/methods and return the
    3. result(s).
    4. ``caller_kwargs`` comes from _HookCaller.__call__().
    5. """
    6. __tracebackhide__ = True
    7. results = []
    8. excinfo = None
    9. try: # run impl and wrapper setup functions in a loop
    10. teardowns = []
    11. try:
    12. for hook_impl in reversed(hook_impls):
    13. try:
    14. args = [caller_kwargs[argname] for argname in hook_impl.argnames]
    15. except KeyError:
    16. for argname in hook_impl.argnames:
    17. if argname not in caller_kwargs:
    18. raise HookCallError(
    19. f"hook call must provide argument {argname!r}"
    20. )
    21. if hook_impl.hookwrapper:
    22. try:
    23. gen = hook_impl.function(*args)
    24. next(gen) # first yield
    25. teardowns.append(gen)
    26. except StopIteration:
    27. _raise_wrapfail(gen, "did not yield")
    28. else:
    29. res = hook_impl.function(*args)
    30. if res is not None:
    31. results.append(res)
    32. if firstresult: # halt further impl calls
    33. break
    34. except BaseException:
    35. excinfo = sys.exc_info()
    36. finally:
    37. if firstresult: # first result hooks return a single value
    38. outcome = _Result(results[0] if results else None, excinfo)
    39. else:
    40. outcome = _Result(results, excinfo)
    41. # run all wrapper post-yield blocks
    42. for gen in reversed(teardowns):
    43. try:
    44. gen.send(outcome)
    45. _raise_wrapfail(gen, "has second yield")
    46. except StopIteration:
    47. pass
    48. return outcome.get_result()

    至此,hook函数调用执行的源码就解析完成了。

    始终坚持开源开放共享精神,同时感谢您的充电鼓励和支持!
    版权所有,转载本站文章请注明出处:redrose2100, http://blog.redrose2100.com/article/494
    个人成就
    • 2022年 : 371 篇 
    • 2023年 : 211 篇 
    • 2024年 : 31 篇 
    • 2025年 : 0 篇 
    • 博客总数: 613 
    • 阅读总量: 639359 
    测试开发技术全栈公众号
    DevOps技术交流微信群