wraps actually has no practical big use, it is to solve the problem that the property of the function that the original function name points to is changed by the adorner;The adorner is decorated over the function func, at which point Func is not pointing to the true func, but rather to the decorated function in the adorner
ImportSysdebug_log=Sys.stderrdefTrace (func):ifDebug_log:defCALLF (*args, * *Kwargs):"""A wrapper function."""Debug_log.write ('calling function: {}\n'. Format (func.__name__)) Res= Func (*args, * *Kwargs) Debug_log.write ('Return value: {}\n'. Format (res))returnResreturnCALLFElse: returnFunc@tracedefSquare (x):"""Calculate The square of the given number.""" returnX * x the square here actually points to calls, which can be viewed with help (square) or square.__name__. Square's decorated function is actually a different function (function names and other functions will change) If you use wraps to decorate
defTrace (func):ifdebug_log: @functools. Wraps (func)defCALLF (*args, * *Kwargs):"""A wrapper function."""Debug_log.write ('calling function: {}\n'. Format (func.__name__)) Res= Func (*args, * *Kwargs) Debug_log.write ('Return value: {}\n'. Format (res))returnResreturnCALLFElse: returnFunc
The properties of square decorated with trace will not change, so help (square) to see
Reason: We translate the code of wraps's decoration as follows, which is equivalent to:
defTrace (func):ifDebug_log:def_CALLF (*args, * *Kwargs):"""A wrapper function."""Debug_log.write ('calling function: {}\n'. Format (func.__name__)) Res= Func (*args, * *Kwargs) Debug_log.write ('Return value: {}\n'. Format (res))returnRes callf= Functools.Update_wrapper(_CALLF,wrapped = Func, assigned = Functools. wrapper_assignments,updated =Functools. Wrapper_updates)returnCALLFElse: returnFunc
Update_wrapper 's work is simple: some properties of the function object (for example: square) represented by the parameter wrapped (e.g., __name__, __doc__) Overriding the function object represented by the parameter wrapper (for example: Callf, where CALLF simply calls the square function, so it can be said that CALLF is a wrapper function of square) these corresponding properties.
So, in this example, with the wraps adorner "decorated" over Callf, CALLF's __doc__, __name__, and so on, are exactly the same as those of the function square where the trace is "decorated."
Learning Notes 2-functools.wraps Decorators