How to find the name of a variable that was passed to a function?

前端 未结 3 1466
囚心锁ツ
囚心锁ツ 2020-12-09 06:14

In C/C++, I have often found it useful while debugging to define a macro, say ECHO(x), that prints out the variable name and its value (i.e. ECHO(variable

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 06:58

    Not really solution, but may be handy (anyway you have echo('foo') in question):

    def echo(**kwargs):
        for name, value in kwargs.items():
            print name, value
    
    foo = 7
    echo(foo=foo)
    

    UPDATE: Solution for echo(foo) with inspect

    import inspect
    import re
    
    def echo(arg):
        frame = inspect.currentframe()
        try:
            context = inspect.getframeinfo(frame.f_back).code_context
            caller_lines = ''.join([line.strip() for line in context])
            m = re.search(r'echo\s*\((.+?)\)$', caller_lines)
            if m:
                caller_lines = m.group(1)
            print caller_lines, arg
        finally:
            del frame
    
    foo = 7
    bar = 3
    baz = 11
    echo(foo)
    echo(foo + bar)
    echo((foo + bar)*baz/(bar+foo))
    

    Output:

    foo 7
    foo + bar 10
    (foo + bar)*baz/(bar+foo) 11
    

    It has the smallest call, but it's sensitive to newlines, e.g.:

    echo((foo + bar)*
          baz/(bar+foo))
    

    Will print:

    baz/(bar+foo)) 11
    

提交回复
热议问题