将包装器应用于函数会阻止它
Applying wrapper to a function brakes it
我正在尝试创建包装器。我的代码适用于简单的示例函数,但是当我将它应用于示例函数时,它停止工作。
我的包装代码:
import functools
import time
from functools import wraps
def profiler(func):
@wraps(func)
def wrapper(*args, **kwds):
setattr(func, 'calls', 0)
t1 = time.monotonic() # what's time at the beginning of run
func(*args, **kwds)
func.calls += 1 # add 1 to number of calls
t2 = time.monotonic() # what's time at the beginning of run
last_time_taken = t2 - t1
setattr(wrapper, 'last_time_taken', last_time_taken)
setattr(wrapper, 'calls', func.calls)
return wrapper
我很乐意得到任何有助于解决此错误的建议。谢谢!
您的包装器没有 return,这与 returning None
相同。当你调用装饰函数时,你实际上只是 运行 包装器。
确保包装器 return 是您函数的结果,它会正常工作。
import functools
import time
from functools import wraps
def profiler(func):
@wraps(func)
def wrapper(*args, **kwds):
setattr(func, 'calls', 0)
t1 = time.monotonic() # what's time at the beginning of run
res = func(*args, **kwds)
func.calls += 1 # add 1 to number of calls
t2 = time.monotonic() # what's time at the beginning of run
last_time_taken = t2 - t1
setattr(wrapper, 'last_time_taken', last_time_taken)
setattr(wrapper, 'calls', func.calls)
return res
return wrapper
我正在尝试创建包装器。我的代码适用于简单的示例函数,但是当我将它应用于示例函数时,它停止工作。
我的包装代码:
import functools
import time
from functools import wraps
def profiler(func):
@wraps(func)
def wrapper(*args, **kwds):
setattr(func, 'calls', 0)
t1 = time.monotonic() # what's time at the beginning of run
func(*args, **kwds)
func.calls += 1 # add 1 to number of calls
t2 = time.monotonic() # what's time at the beginning of run
last_time_taken = t2 - t1
setattr(wrapper, 'last_time_taken', last_time_taken)
setattr(wrapper, 'calls', func.calls)
return wrapper
我很乐意得到任何有助于解决此错误的建议。谢谢!
您的包装器没有 return,这与 returning None
相同。当你调用装饰函数时,你实际上只是 运行 包装器。
确保包装器 return 是您函数的结果,它会正常工作。
import functools
import time
from functools import wraps
def profiler(func):
@wraps(func)
def wrapper(*args, **kwds):
setattr(func, 'calls', 0)
t1 = time.monotonic() # what's time at the beginning of run
res = func(*args, **kwds)
func.calls += 1 # add 1 to number of calls
t2 = time.monotonic() # what's time at the beginning of run
last_time_taken = t2 - t1
setattr(wrapper, 'last_time_taken', last_time_taken)
setattr(wrapper, 'calls', func.calls)
return res
return wrapper