如何统计Python中retry装饰器重试函数的调用次数
统计retry装饰器的函数调用次数
要实现统计重试装饰器中目标函数的调用次数,可以通过给被装饰后的函数绑定计数器属性的方式来实现,以下是修改后的完整代码:
修改后的retry装饰器
import time from functools import wraps def retry(tries=3, delay=10): def decorator(func): @wraps(func) def func_retry(*args, **kwargs): # 每次执行被装饰函数时重置计数器 func_retry.call_count = 0 n_tries, n_delay = tries, delay output = error = None while n_tries >= 1: try: # 每次调用原函数前递增计数器 func_retry.call_count += 1 output = func(*args, **kwargs) return output except AssertionError as e: n_tries -= 1 error = str(e) print(f'Retry error: "{func.__name__}" due to "{error}". So, Retrying execution [{(tries - n_tries)}/{tries}] in {delay} second(s)...') time.sleep(n_delay) return output # 初始化计数器属性,避免首次访问报错 func_retry.call_count = 0 return func_retry return decorator
测试用例与调用次数获取
@retry() def test(): assert "x" == "y" # 执行测试函数 try: test() except AssertionError: pass # 获取并打印调用次数 print(f"test函数总共被调用了{test.call_count}次")
说明
- 给被装饰后的函数对象添加了
call_count属性,每次调用原函数前会自动递增计数器。 - 每次执行被装饰的函数时,计数器会先重置为0,确保单次函数调用的统计独立。
- 可以直接通过被装饰的函数名(如
test.call_count)获取该函数的总调用次数。
内容的提问来源于stack exchange,提问作者Mahesh
相关产品推荐
相关产品推荐

