Python-获取全局范围内对象的所有变量名

Python-获取全局范围内对象的所有变量名,python,Python,我将用一个例子来解释: list_1 = [1, 2, 3] list_2 = list_3 = list_1 # reference copy print(magic_method(list_1)) # Should print ['list_1', 'list_2', 'list_3'] set_1 = {'a', 'b'} print(magic_method(set_1)) # Should print ['set_1'] 要求:返回指向同一引用的所有变量的名称。这在python中

我将用一个例子来解释:

list_1 = [1, 2, 3]
list_2 = list_3 = list_1 # reference copy

print(magic_method(list_1))
# Should print ['list_1', 'list_2', 'list_3']

set_1 = {'a', 'b'}
print(magic_method(set_1))
# Should print ['set_1']
要求:返回指向同一引用的所有变量的名称。这在python中是可能的吗

我在考虑迭代
globals()
locals()
并将
id
s等同起来。还有更好的吗?

这很有效:

def magic_method(var):
     names = filter(lambda x: globals()[x] is var, globals().keys())
     return names

is
执行参考比较。如果您使用的是Python3,请将
列表(…)
添加到结果表达式中。

对于全局变量,您可以执行以下操作:

def magic_method(obj):
    return [name for name, val in globals().items() if val is obj]
如果您还需要本地名称,可以使用模块:

然后:

list_1 = [1, 2, 3]
list_2 = list_1

def my_fun():
    list_3 = list_1
    list_2 = list_1
    print(magic_method(list_1))

my_fun()
>>> ['list_3', 'list_1', 'list_2']

闭包也很有趣吗?@donkopotamus我认为不需要太复杂。我现在只考虑全局范围。对于全局范围
globals()。当我们有
is
时,不需要比较ID。那么其他容器、类等下的引用呢<代码>列表_4=[列表_1,0];A类:foo=list_1
。一种基于gc的递归解决方案。获取\u referers?但这将是非常非常棘手的,而且很可能是不可能的。例如,请检查以下内容:<代码>[[1,2,3],0]和
'list_4':[[1,2,3],0]
是两个独立的条目,但实际上是相同的引用。有
'foo':[1,2,3]
,但是谁包含
foo
?最后,对于插槽,它简单地说:
。应该使用
is
not
=
好的,它不是相同的引用,而是相同的值,更改
=
for
is
以获得引用问题是关于同一对象的。两张不同的100美元钞票不是同一张纸币。@cᴏʟᴅsᴘᴇᴇᴅ 我已经将答案更新为包含局部变量。请注意,这仅适用于调用
magic\u方法的函数中的局部变量。如果调用堆栈上还有更多的函数,它们将被忽略。你可以循环调用堆栈直到
frame.f_back
返回
None
@Rawing是的,你是对的,我假设只有来自直接调用方的局部变量会感兴趣,但是你也可以像那样检查整个堆栈。如果你将函数调用为magic_method(),它会返回环境中所有的全局方法吗?@anitasp你的意思是像
magic\u method()
那样没有参数?这是行不通的,函数在编写时需要一个参数。你所说的“环境中的所有全局方法”是什么意思?
list_1 = [1, 2, 3]
list_2 = list_1

def my_fun():
    list_3 = list_1
    list_2 = list_1
    print(magic_method(list_1))

my_fun()
>>> ['list_3', 'list_1', 'list_2']