使用@get_time装饰器后Python函数无法返回值的问题
问题原因
你的@get_time装饰器的wrapper函数中,调用原函数func(*args, **kwargs)后没有返回其结果,导致装饰后的get_list_of_files函数默认返回None,而非原函数生成的文件列表。
修复方案
修改get_time装饰器的wrapper函数,保存原函数的返回值并在最后返回:
def get_time(func): from time import perf_counter from functools import wraps """Times any function""" @wraps(func) def wrapper(*args, **kwargs): start_time = perf_counter() # 保存原函数的返回结果 result = func(*args, **kwargs) end_time = perf_counter() total_time = round(end_time - start_time, 5) print(func.__name__) print(f"Took {total_time} seconds") # 返回原函数的结果 return result return wrapper
验证效果
修改后调用get_list_of_files,既能输出函数执行时间,也能正常获取到匹配的文件列表,print(all_files)会正确打印结果。
内容的提问来源于stack exchange,提问作者Broxy
相关产品推荐
相关产品推荐

