python3一个给文件所有函数加装饰器的方法

比如要打印某文件中所有函数的执行时间

import time
import inspect
from xxx import log

def time_it(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        log("Function %s took %s seconds to execute." %(func.__name__, end_time - start_time))
        return result
    return wrapper

def decorate_current_module_functions():
    current_module = inspect.getmodule(inspect.currentframe())
    for name, obj in inspect.getmembers(current_module):
        if inspect.isfunction(obj):
            if obj.__name__ != "log": # 因为time_it里面使用了log,所以这里要剔除掉log,不然会出现无限递归。(如果是使用print就没问题,time_it里面如果调用别的函数,就得剔除掉,不然递归了)
                globals()[name] = time_it(obj)

def fun1():
    time.sleep(1)

def fun2():
    time.sleep(2)

# 给当前模块中的所有函数添加装饰器
decorate_current_module_functions()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值