如何获取函数/方法的调用参数值?
它用于调试工具,它将用于如下场景:
import inspect
def getCallParameter():
stack = inspect.stack()
outer = stack[1] #This is an example, I have a smarter way of finding the right frame
frame = outer.frame
print("") #print at least a dict of the value of the parameters, and at best, give also which parameter are passed explicitly (e.g. with f(2, 4) an input of this kind : "a=2, b=4, c=5(default)")
def f(a, b=4, c=5):
a+=b+c
getCallParameters()
return a
注意:我知道inspect.formatargsvalues()
但它不符合我的要求,因为在f(2,4)
示例中,它会打印"a=11, b=4, c=5(">
我想的是,在外部框架上观察传递的值。如果我没有得到传递对象的原始状态,这不是问题,只要我得到最初绑定到变量参数的对象。
例:
# with f(4)
def f(a, b=4, c=[])
c.append(5)
getCallParameters() # a=4, b=4, c=[5] is ok even if I would have preferred c=[]
c = [4]
getCallParameters() # here, I expect c=[5] or c=[]
我有一种不同的方法来应对查找传递的确切参数,但我确实想知道它是否与您的调试工具兼容。这样可以很好地处理函数的调用方式。尽管如此,应该使用诸如
inspect
之类的东西来检索实际帧参数。
def inspect_decorator(func): # decorator
def wrapper(*args, **kwargs): # wrapper function
# TODO: don't print! consume somewhere else
print('{} is called with args={} kwargs={}'.format(func.__name__, args, kwargs))
return func(*args, **kwargs) # actual execution
return wrapper # wrapped function
@inspect_decorator
def f(a, b=4, c=5):
a += b + c
return a
f(3)
f(3, 5)
f(3, b=4)
# f is called with args=(3,) kwargs={}
# f is called with args=(3, 5) kwargs={}
# f is called with args=(3,) kwargs={'b': 4}
在 TODO 部分中,您可以使用上下文堆栈来跟踪感兴趣的每个函数。但同样,这取决于你对整个项目做了什么。