Python Dunder方法可打印函数包含的所有变量?对于自定义调试装饰器

时间:2019-01-21 00:41:01

标签: python-3.6

有没有一种方法可以打印出函数的所有变量?我想构建一个自定义的调试装饰器,但似乎找不到我想要的东西。我假设为此有一些笨拙的方法?因此对于功能:

def debugger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(func.__funcVariables__) #Some dunder method that Prints all variables contained in func
        return func
    return wrapper

@debugger
def my_func():
    x = 'foo'
    y = 'bar'

我希望从装饰器将“ foo”和“ bar”打印到控制台。我该如何实现?

1 个答案:

答案 0 :(得分:1)

听起来您正在寻找function.__code__.co_varnames,它是函数参数和局部变量名称的元组。 documentation for the inspect module

中的其余代码自省工具对此进行了记录。
def debugger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(func.__code__.co_varnames) 
        return func
    return wrapper

@debugger
def my_func():
    x = 'foo'
    y = 'bar'