如何查看引用对象的所有变量?

How can I view all of the variables that refer to an object?

以我对Python的理解,当我赋值

A = 1

变量 A 是对具有值 1 的对象的引用,其他变量也可以引用该对象。

如何view/print/return引用该对象的所有变量?

首先,得到一个dictionary of all variables currently in scope and their values

d = dict(globals(), **locals())

然后创建字典中所有引用的列表,其中值与您感兴趣的对象相匹配:

[ref for ref in d if d[ref] is obj]

例如:

A = [1,2,3]
B = A
C = B
d = dict(globals(), **locals())
print [ref for ref in d if d[ref] is C]

输出:

['A', 'C', 'B']