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

如何用Python装饰器批量修改函数行为?含计时与错误处理需求

实现兼具执行时间记录与错误捕获的Python装饰器

你可以创建一个通用装饰器,同时满足执行时间统计和异常捕获记录的需求,以下是完整实现示例:

装饰器代码实现

import time
import functools

def function_monitor(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # 记录函数开始执行时间
        start_time = time.perf_counter()
        try:
            # 执行原函数
            result = func(*args, **kwargs)
            # 计算执行耗时
            execution_time = time.perf_counter() - start_time
            print(f"[INFO] 函数 {func.__name__} 执行成功,耗时: {execution_time:.6f} 秒")
            return result
        except Exception as e:
            # 捕获异常并计算耗时
            execution_time = time.perf_counter() - start_time
            print(f"[ERROR] 函数 {func.__name__} 执行失败,耗时: {execution_time:.6f} 秒")
            print(f"[ERROR] 错误类型: {type(e).__name__},错误详情: {str(e)}")
            # 若需要将异常继续向上抛出,取消下方注释
            # raise
    return wrapper

关键细节说明

  • functools.wraps(func):保留原函数的名称、文档字符串等元信息,避免装饰后函数标识被覆盖
  • time.perf_counter():采用高精度计时器,适合统计短时间函数的执行耗时
  • *args, **kwargs:适配任意参数签名的函数,确保装饰器具备通用性
  • 异常捕获块:捕获所有Exception类型的错误(可根据需求限制特定异常),同时记录错误发生时的执行耗时

应用装饰器到你的函数

直接在目标函数上方添加@function_monitor装饰器即可:

@function_monitor
def my_function(numbers):
    odd_numbers = [n for n in numbers if n % 2 != 0]
    result = sum(odd_numbers)
    return result

@function_monitor
def reverse_sentence(sentence):
    words = sentence.split()
    reversed_sentence = ' '.join(reversed(words))
    return reversed_sentence

测试示例

正常执行场景

# 测试奇数求和函数
print(my_function([1, 2, 3, 4, 5]))
# 输出:
# [INFO] 函数 my_function 执行成功,耗时: 0.000011 秒
# 9

# 测试单词反转函数
print(reverse_sentence("Hello World Python"))
# 输出:
# [INFO] 函数 reverse_sentence 执行成功,耗时: 0.000007 秒
# Python World Hello

异常执行场景

# 传入非列表参数触发错误
my_function("invalid input")
# 输出:
# [ERROR] 函数 my_function 执行失败,耗时: 0.000005 秒
# [ERROR] 错误类型: TypeError,错误详情: not all arguments converted during string formatting

# 传入非字符串参数触发错误
reverse_sentence(12345)
# 输出:
# [ERROR] 函数 reverse_sentence 执行失败,耗时: 0.000004 秒
# [ERROR] 错误类型: AttributeError,错误详情: 'int' object has no attribute 'split'

扩展建议

  • 生产环境优化:用logging模块替代print,将日志写入文件或日志系统,便于后续排查问题
  • 自定义配置:让装饰器接受参数(如日志级别、是否抛出异常),进一步提升灵活性
  • 上下文记录:添加函数参数、返回值的日志记录,方便调试复杂函数

内容的提问来源于stack exchange,提问作者Ieleniayu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:57:03