Search code examples
pythonpython-2.7decoratorpython-decorators

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


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?


Solution

  • 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.