python获取变量的名称来辅助调试,两种方法

只列举两种方法

#打印变量名
import inspect
import sys
import re
import traceback

pattren = re.compile(r'[\W+\w+]*?get_name_1\((\w+)\)')  # 注意和函数名一致
__get_variable_name__ = []
def get_name_1(x):
    '''
    第一种,复杂一些,需要声明两个全局变量,容易引发bug,但功能强一些
    '''
    global __get_variable_name__
    if not __get_variable_name__:
        __get_variable_name__ = pattren.findall(
            traceback.extract_stack(limit=2)[0][3])
    return __get_variable_name__.pop(0)

def get_name_2(var):
    '''
    第二种,简单,没那么好用,不容易引发其他bug
    '''
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]


if __name__ == "__main__":
    a = 1
    b = a
    c = b
    d = list(range(7))

    print(get_name_1(a))
    print(get_name_1(b))
    print(get_name_1(c))
    print([get_name_1(a), get_name_1(b), get_name_1(c)])
    for i in d:
        print(get_name_1(i), '=', i)

    print(get_name_2(a))
    print(get_name_2(b))
    print(get_name_2(c))
    print([get_name_2(a), get_name_2(b), get_name_2(c)])
    for i in d:
        print(get_name_2(i), '=', i)

 

运行结果:

 

posted @ 2020-04-03 15:14  nervending  阅读(506)  评论(0编辑  收藏  举报