This article is mainly for you in detail how Python preserves the metadata of the decorated function, hoping to help everyone.
Case:
The metadata for some functions is stored in the function object, such as:
Name of f.__name__ function
f.__doc__ function Documentation
f.__moudle__ function belongs to module name
f.__dict__ Property Dictionary
f.__defaults__ Default parameter groups
......
When you access the above properties in the adorner after using the adorner, we see the metadata for the adorner function
Requirements:
Implementation in the adorner function, preserving the metadata of the decorated function
How is it implemented?
Through the wraps in Functools, the Update_wrapper method is implemented, each can be implemented independently
#!/usr/bin/python3 import timefrom functools import (wraps, Update_wrapper, Wrapper_assignments, Wrapper_updates) def count_time (func): "" "Add calculation run time statistics to the target function" "# This loader and update_wrapper, the default parameter wrap Per_assignments, Wrapper_updates @wraps (func) def WRAPPER (*args, **kwargs): Start_time = time.time () # definition ResU LT receives the function return value and returns back to Resutl = Func (*args, **kwargs) print (' Run time: ', Time.time ()-start_time) at the end of the adornment function return Resutl # Where default parameter wrapper_assignments, Wrapper_updates # update_wrapper (WRAPPER, func) return WRAPPER @count_timedef Add (num=100) : "" Calculates 0~num cumulative value, default num=100 "" "" "Time.sleep (1) return sum ([x for X in range (num+1)]) if __name__ = = ' __main__ ': prin T (' Function name: ', add.__name__) print (' Property dictionary: ', add.__dict__) print (' function default parameter: ', add.__defaults__) ' Print (' function module: ', Add.__module __) Print (' Function document: ', add.__doc__) # prints two default parameters print (wrapper_assignments, wrapper_updates) result = Add () print (Result )