What is the correct way to decorate an external (library) function?

淺唱寂寞╮ 提交于 2021-01-24 07:30:30

问题


I'm using a library function several times in my code which tests for a pass/fail condition and executes different code accordingly, but for some reason does not have a return value for the result it finds; I'd like to add this with a decorator so that I can call it in my code.

What is the correct way to do this given that I cannot edit the source file?

Should I do something like:

def test_pass(param1, param2):
    external_function(param1, param2)
    if(...):
        return False
    else:
        return True

Or is there a way to use the nice @decorator syntax?


回答1:


Decorating with @decorator is syntactic sugar; the function object is replaced by whatever the decorator(orig_function) call returns.

For external functions, you'd just use the wrapper you wrote; you'd only use the decorator syntax when defining the original function.



来源:https://stackoverflow.com/questions/25240221/what-is-the-correct-way-to-decorate-an-external-library-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!