1

如何获取函数/方法的调用参数的值?

它是一个调试工具,它会在这样的场景中使用:

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 wich parameter are passed explicitely (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 exepect c=[5] or c=[]
4

1 回答 1

1

我有一种不同的方式来处理查找传递的确切参数,但我想知道它是否与您的调试工具兼容。这很好地照顾了函数的调用方式。尽管如此,应该使用诸如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 部分,您可以使用上下文堆栈来跟踪每个感兴趣的函数。但同样,这取决于您对整个项目所做的工作。

于 2018-04-30T13:53:58.430 回答