You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:10:19