列表中对象的名称?

Names of objects in a list?

我正在尝试将字典迭代写入文件,但在为每个字典创建唯一文件名时遇到问题。

def variable_to_value(value):
    for n, v in globals().items():
        if v == value:
            return n
    else: 
        return None

a = {'a': [1,2,3]}
b = {'b': [4,5,6]}
c = {'c': [7,8,9]}

for obj in [a, b, c]:
    name = variable_to_value(obj)
    print(name)

这会打印:

a
obj
obj

如何访问原始对象本身的名称而不是 obj

Python 实际上并不是这样工作的。

Python 中的对象没有固有名称。这是属于一个对象的名称,而不是相反:一个对象可以有很多名称(或根本没有名称)。

您将打印两份 "obj",因为在您调用 variable_to_value 时,名称 b 和名称 obj 都引用同一个对象! (字典 {'b': [4,5,6]})因此,当您在全局命名空间中搜索等于 obj 的任何值时(请注意,您应该使用 is 而不是 == 进行检查)无论你得到 b 还是 obj.

实际上都是随机的

函数 returns 它找到引用您 globals() 中对象的名字。但是,在每次迭代中,名称 obj 将引用每个对象。因此,要么返回名称 abc,要么返回 obj,具体取决于在 globals().

中第一个到达的名称

您可以通过在函数的搜索中排除该名称来避免返回 obj - 有点骇人听闻:

def variable_to_value(value):
    for n, v in globals().items():
        if v == value and n != 'obj':
            return n
    else: 
        return None

问题是obj,你的迭代变量也在globals。无论你得到 a 还是 obj 只是运气。你不能解决一般的问题,因为一个对象可以在全局变量中有任意数量的赋值。您可以更新您的代码以排除已知引用,但这非常脆弱。

例如

a = {'a': [1,2,3]}
b = {'b': [4,5,6]}
c = {'c': [7,8,9]}

print("'obj' is also in globals")

def variable_to_value(value):
    return [n for n,v in globals().items() if v == value]

for obj in [a, b, c]:
    name = variable_to_value(obj)
    print(name)

print("you can update your code to exclude it")

def variable_to_value(value, exclude=None):
    return [n for n,v in globals().items() if v == value and n != exclude]

for obj in [a, b, c]:
    name = variable_to_value(obj, 'obj')
    print(name)

print("but you'll still see other assignments")

foo = a
bar = b
bax = c

for obj in [a, b, c]:
    name = variable_to_value(obj, 'obj')
    print(name)

当运行

'obj' is also in globals
['a', 'obj']
['b', 'obj']
['c', 'obj']
you can update your code to exclude it
['a']
['b']
['c']
but you'll still see other assignments
['a', 'foo']
['b', 'bar']
['c', 'bax']

所以您想查找 globals() 中可用的任何对象的名称?

for 循环中,globals() dict 正在发生变化,在其命名空间中添加 obj。所以在你的第二遍中,你有两个对同一个对象的引用(最初只通过名称 'a')引用。

使用 globals() 的危险,我想。