获取当前模块内的所有函数,并为每个函数自动加装装饰器

示例代码,用来,获取当前模块内的所有函数名,在为每个函数加装饰器。

 1 import sys
 2 import time
 3 from inspect import isfunction
 4 
 5 def timer(func):
 6     def wrapper(*args, **kwargs):
 7         start = time.time()
 8         getattr(sys.modules['__main__'],func)(*args, **kwargs)
 9         print('function %s run time %s' % (func, time.time() - start))
10     return wrapper
11 def foo():
12     time.sleep(0.2)
13     print('function foo')
14 def bar():
15     time.sleep(0.1)
16     print('function bar')
17 def f1():
18     time.sleep(0.1)
19     print('function f1')
20 
21 for func in dir():
22     try:
23         if func != 'timer' and isfunction(eval(func)) and func != 'isfunction':
24             timer(func)()
25     except TypeError:
26             pass
27 
28 '''
29     function bar
30     function bar run time 0.10009121894836426
31     function f1
32     function f1 run time 0.10005760192871094
33     function foo
34     function foo run time 0.2008991241455078
35 '''
View Code

End

猜你喜欢

转载自www.cnblogs.com/Neeo/p/9146695.html