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
Import Sysdebug_log = Sys.stderrdef Trace (func): if Debug_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)) return res return CALLF else: return func@tracedef Square (x): "" " Calculate the square of the given Number. "" " return x * 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
def Trace (func): if Debug_log: @functools. Wraps (func) 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)) return res return CALLF else: return func
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:
def Trace (func): if Debug_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)) return res CALLF = functools.update_wrapper (_CALLF, wrapped = func,assigned = Functools. wrapper_assignments,updated = Functools. wrapper_updates) return callf else: return func
The work done by Update_wrapper is simply to override the function object represented by the parameter wrapper (for example: __name__, __doc__) with some of the properties of the function object represented by the parameter wrapped (for example: square), such as CALLF. Here CALLF simply calls the square function, so it can be said that CALLF is one of the wrapper functions of square) with 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."