我希望能够以字符串的形式获取变量的名称,但我不知道Python是否有那么多的自省功能。喜欢的东西:

>>> print(my_var.__name__)
'my_var'

我想这样做是因为我有一堆变量,我想把它们转换成一个字典,比如:

bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict 
{'foo': False, 'bar': True}

但我想要更自动的。

Python有locals()和vars(),所以我猜有一种方法。


当前回答

在python 2.7及更新版本中,还有字典理解,这使得它更短一些。如果可能的话,我会使用getattr代替eval (eval是邪恶的),就像在顶部的答案。Self可以是任何有你正在看的上下文的对象。它可以是一个对象或locals=locals()等。

{name: getattr(self, name) for name in ['some', 'vars', 'here]}

其他回答

好吧,几天前我遇到了同样的需求,必须获得一个指向对象本身的变量名。

为什么这么有必要呢?

In short I was building a plug-in for Maya. The core plug-in was built using C++ but the GUI is drawn through Python(as its not processor intensive). Since I, as yet, don't know how to return multiple values from the plug-in except the default MStatus, therefore to update a dictionary in Python I had to pass the the name of the variable, pointing to the object implementing the GUI and which contained the dictionary itself, to the plug-in and then use the MGlobal::executePythonCommand() to update the dictionary from the global scope of Maya.

为了做到这一点,我所做的是:

import time

class foo(bar):

    def __init__(self):
        super(foo, self).__init__()
        self.time = time.time() #almost guaranteed to be unique on a single computer

    def name(self):
        g = globals()
        for x in g:
            if isinstance(g[x], type(self)):
                if g[x].time == self.time:
                    return x
                    #or you could:
                    #return filter(None,[x if g[x].time == self.time else None for x in g if isinstance(g[x], type(self))])
                    #and return all keys pointing to object itself

我知道这不是一个完美的解决方案,在全局许多键可以指向同一个对象,例如:

a = foo()
b = a
b.name()
>>>b
or
>>>a

而且这种方法不是线程安全的。如果我错了,请指正。

至少这种方法解决了我的问题,它在全局作用域中获取指向对象本身的任何变量的名称,并将其作为参数传递给插件,供它在内部使用。

我在int(原始整数类)上尝试了这一点,但问题是这些原始类不会被绕过(请纠正使用的技术术语,如果它是错误的)。你可以重新实现int,然后执行int = foo,但a = 3永远不会是foo的对象,而是原语的对象。为了克服这个问题,你必须使用a = foo(3)来让a.name()工作。

import re
import traceback

pattren = re.compile(r'[\W+\w+]*get_variable_name\((\w+)\)')
def get_variable_name(x):
    return pattren.match( traceback.extract_stack(limit=2)[0][3]) .group(1)

a = 1
b = a
c = b
print get_variable_name(a)
print get_variable_name(b)
print get_variable_name(c)

这是一个黑客。它不能在所有Python实现发行版上工作(特别是那些没有traceback.extract_stack的发行版)。

import traceback

def make_dict(*expr):
    (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
    begin=text.find('make_dict(')+len('make_dict(')
    end=text.find(')',begin)
    text=[name.strip() for name in text[begin:end].split(',')]
    return dict(zip(text,expr))

bar=True
foo=False
print(make_dict(bar,foo))
# {'foo': False, 'bar': True}

注意,这个黑客是脆弱的:

make_dict(bar,
          foo)

(在2行上调用make_dict)将无法工作。

与其尝试用foo和bar值生成dict, 从字符串变量名'foo'和'bar'中生成dict会更加python化:

dict([(name,locals()[name]) for name in ('foo','bar')])

下面是我创建的读取变量名的函数。它更通用,可以用于不同的应用:

def get_variable_name(*variable):
    '''gets string of variable name
    inputs
        variable (str)
    returns
        string
    '''
    if len(variable) != 1:
        raise Exception('len of variables inputed must be 1')
    try:
        return [k for k, v in locals().items() if v is variable[0]][0]
    except:
        return [k for k, v in globals().items() if v is variable[0]][0]

在特定的问题中使用:

>>> foo = False
>>> bar = True
>>> my_dict = {get_variable_name(foo):foo, 
               get_variable_name(bar):bar}
>>> my_dict
{'bar': True, 'foo': False}

我上传了一个解决方案到pypi。它是一个模块,定义了c#的nameof函数的等价物。

它遍历被调用帧的字节码指令,获取传递给它的变量/属性的名称。这些名称可以在函数名后面的LOAD指令的.argrepr中找到。