Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

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

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) might print variable 7). You can get the variable name in a macro using the 'stringification' operator # as described here. Is there a way of doing this in Python?

In other words, I would like a function

def echo(x):
    #magic goes here

which, if called as foo=7; echo(foo) (or foo=7; echo('foo'), maybe), would print out foo 7. I realise it is trivial to do this if I pass both the variable and its name to the function, but I use functions like this a lot while debugging, and the repetition always ends up irritating me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'echos*((.+?))$', 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...