Skip to content Skip to sidebar Skip to footer

Python Decorator With Arguments Of Decorated Function

When I wrap a function with @, how do I make the wrapper function look & feel exactly like the wrapped function? help(function) in particular. Some code: >>> def wraps

Solution 1:

functools.wraps can be used to copy the name and docstring of the function. Copying the original function signature is considerably harder to do from scratch.

If you use the third-party decorator module, however, then

import decorator


@decorator.decoratordefwraps(f):
    defcall(*args, **kw):
        print('in', f, args, kw) 
        return f(*args, **kw)
    return call


defg():pass@wrapsdeff(a, b = 1, g = g, *args, **kw):
    passhelp(f)

yields

Help onfunction f inmodule __main__:

f(a, b=1, g=<function g>, *args, **kw)

Solution 2:

Use functools.wraps:

from functools import wraps

defwrapper(f):
    @wraps(f)defcall(*args, **kw):
        print('in', f, args, kw)
        return f(*args, **kw)
    return call

@wrapperdeff(a, b = 1, g = g, *args, **kw):
    passhelp(f)
Help on function f in module __main__:

f(a, b=1, g=<function g at 0x7f5ad14a6048>, *args, **kw)

This preserves the __name__ and __doc__ attributes of your wrapped function.

Solution 3:

I think the other answers are preferable, but if for some reason you don't want to use an external module, you could always alter your decorator like so:

defwraps(f):
  defcall(*args, **kw):
    print('in', f, args, kw)
    return f(*args, **kw)
call.__name__ = f.__name__
call.__doc__ = f.__doc__
return call

Post a Comment for "Python Decorator With Arguments Of Decorated Function"