我有一个模块mymod
,它定义了十几个具有相同签名的函数
def myfun1 (a,b,c):
...
return d
我想跟踪所有这些函数:
def traced (f):
def wrapped (a,b,c):
print ">>>%s(%d)" % (f.__name__, (a+b)/c)
d = f(a,b,c)
print "<<<%s(%g)" % (f.__name__, 1/d)
return d
return wrap
@traced
def myfun1 (a,b,c):
...
return d
(此处(a+b)/c
和1/d
是更复杂的东西的替身。)
除了在函数定义之前添加@traced
之外,还有更优雅的方法吗?
PS。 5年前问过similar question。我想知道是否有新的答案。
答案 0 :(得分:0)
通过浏览globals()
dict,有可能:
def myfun1 (a,b,c):
return 1.+a+b+c
def myfun2 (a,b,c):
return 1.+a+b-c
def traced (f):
def wrapped (a,b,c):
print ">>>%s(%d)" % (f.__name__, (a+b)/c)
d = f(a,b,c)
print "<<<%s(%g)" % (f.__name__, 1/d)
return d
return wrapped
print 'myfun1(1,2,3): ', myfun1(1,2,3)
print 'myfun2(1,2,3): ', myfun2(1,2,3)
import types
for x in globals().copy(): # copy() is mandatory because globals() is being updated
if x == 'traced' or x.startswith('__'): # Ignore trace function and private ones
continue
if isinstance(globals()[x], types.FunctionType):
print "Found function:", x
globals()[x] = traced(globals()[x])
print 'myfun1(1,2,3): ', myfun1(1,2,3)
print 'myfun2(1,2,3): ', myfun2(1,2,3)
结果:
myfun1(1,2,3): 7.0
myfun2(1,2,3): 1.0
Found function: myfun1
Found function: myfun2
myfun1(1,2,3): >>>myfun1(1)
<<<myfun1(0.142857)
7.0
myfun2(1,2,3): >>>myfun2(1)
<<<myfun2(1)
1.0