如何找到传递给函数的变量的名称? [英] How to find the name of a variable that was passed to a function?

查看:36
本文介绍了如何找到传递给函数的变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C/C++ 中,我经常发现在调试时定义一个宏很有用,比如 ECHO(x),它打印出变量名称及其值(即 ECHO(variable) 可能会打印 variable 7).您可以使用字符串化"运算符 # 在宏中获取变量名称,如 此处.有没有办法在 Python 中做到这一点?

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

其中,如果调用为 foo=7;echo(foo)(或 foo=7; echo('foo'),也许),会打印出 foo 7.我意识到如果我将变量及其名称都传递给函数,这样做很简单,但我在调试时经常使用这样的函数,而重复总是让我恼火.

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.

推荐答案

不是真正的解决方案,但可能很方便(无论如何你有 echo('foo') 问题):

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)

更新:echo(foo)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))

输出:

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))

将打印:

baz/(bar+foo)) 11

这篇关于如何找到传递给函数的变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆