Home >Backend Development >Python Tutorial >How to Preserve the Signature of Decorated Functions in Python?
Decorators are powerful tools in Python for extending the behavior of existing functions. However, when applied to a function, the resulting decorated function often loses its original documentation and signature. This can be problematic, especially when using generic decorators that perform common tasks like logging or argument conversion.
Common Workarounds
Some common workarounds include:
Using decorator Module
A more robust solution is to use the decorator module, which provides a decorator function called @decorator.decorator. By applying this decorator to your own decorator function, you can preserve the signature of the original function.
<code class="python">import decorator @decorator.decorator def args_as_ints(f, *args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z print(funny_function("3", 4.0, z="5")) # 22 help(funny_function) # Help on function funny_function in module __main__: # # funny_function(x, y, z=3) # Computes x*y + 2*z</code>
Python 3.4
In Python 3.4 and later, the functools.wraps() function can be used to preserve signatures.
<code class="python">import functools def args_as_ints(func): @functools.wraps(func) def wrapper(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return func(*args, **kwargs) return wrapper @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z print(funny_function("3", 4.0, z="5")) # 22 help(funny_function) # Help on function funny_function in module __main__: # # funny_function(x, y, z=3) # Computes x*y + 2*z</code>
The above is the detailed content of How to Preserve the Signature of Decorated Functions in Python?. For more information, please follow other related articles on the PHP Chinese website!