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

后端 未结 6 1226
没有蜡笔的小新
没有蜡笔的小新 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 04:05

    You could inspect the stack trace and "parse" it. Since you know the name of your function (dd in this case) it becomes fairly easy to find the call and extract the name of the variable.

        import inspect
        import re
    
        def dd(value):
            calling_frame_record = inspect.stack()[1]
            frame = inspect.getframeinfo(calling_frame_record[0])
            m = re.search( "dd\((.+)\)", frame.code_context[0])
            if m:
                print "{0} = {1}".format(m.group(1), value)
    
        def test():
            a = 4
            dd(a)
    
        test()
    

    Output

    a = 4
    

提交回复
热议问题