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

前端 未结 3 1459
囚心锁ツ
囚心锁ツ 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:50

    Here's a solution that has you type a bit more to call it. It relies on the locals built-in function:

    def print_key(dictionary, key):
        print key, '=', dictionary[key]
    
    
    foo = 7
    print_key(locals(), 'foo')
    

    An echo with the semantics you mentioned is also possible, using the inspect module. However, do read the warnings in inspect's documentation. This is an ugly non-portable hack (it doesn't work in all implementations of Python). Be sure to only use it for debugging.

    The idea is to look into the locals of the calling function. The inspect module allows just that: calls are represented by frame objects linked together by the f_back attribute. Each frame's local and global variables are available (there are also builtins, but you're unlikely to need to print them).

    You may want to explicitly delete any references frame objects to prevent reference cycles, as explained in inspect docs, but this is not strictly necessary – the garbage collection will free them sooner or later.

    import inspect
    
    def echo(varname):
        caller = inspect.currentframe().f_back
        try:
            value = caller.f_locals[varname]
        except KeyError:
            value = caller.f_globals[varname]
        print varname, '=', value
        del caller
    
    foo = 7
    echo('foo')
    

提交回复
热议问题