Can you translate this debugging macro from C++ to python?

后端 未结 6 1175
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 03:06

I use this very helpful macro when developing in C++:

#define DD(a) std::cout << #a \" = [ \" << a << \" ]\" << std::endl;std::cout.f         


        
6条回答
  •  感情败类
    2021-01-15 03:48

    As @Andrea Spadaccini and @adirau point out, it is not possible to reliably map values back to Python variable names. You could trawl through all namespaces looking for some variable name that references the given value, but that would be fighting the system and liable to return the wrong variable name.

    Much easier it is to just pass the variable name:

    import inspect
    def pv(name):
        frame,filename,line_number,function_name,lines,index=inspect.getouterframes(
            inspect.currentframe())[1]    
        # print(frame,filename,line_number,function_name,lines,index)
        val=eval(name,frame.f_globals,frame.f_locals)
        print('{0}: {1}'.format(name, val))
    
    
    a=5
    pv('a')
    

    yields:

    a: 5
    

提交回复
热议问题