If you want to use a decorator to time, what is the code that should be filled in the blank?

-sharp -*- coding: utf-8 -*-
import time, functools
def metric(fn):
    -sharp 
    def wrapper(*args, **kw):
        startTime = time.time()
        tmp = fn(*args, **kw)
        endTime = time.time()
        print("%s executed in %s s" % (fn.__name__, endTime - startTime ))
        return tmp
    return wrapper

Why do you fill in @ funtools.wraps (fn)?

Apr.05,2021

needs to copy the _ _ name__ and other attributes of the original function into the wrapper () function, otherwise, some code execution that depends on the function signature will go wrong.

Let me explain the answer of joy sheet again. Use this decorator to decorate the function. Print func.__name__ is the name of the wrapper, function has been changed, but if the decorator @ functools.wraps (fn) is added, the print func.__name__ is still the original name of the function

.
Menu