multiprocessing.Manager().dict().setdefault() 是否损坏?

2023-11-25

这个迟来且可能很愚蠢的部门提出:

>>> import multiprocessing
>>> mgr = multiprocessing.Manager()
>>> d = mgr.dict()
>>> d.setdefault('foo', []).append({'bar': 'baz'})
>>> print d.items()
[('foo', [])]         <-- Where did the dict go?

Whereas:

>>> e = mgr.dict()
>>> e['foo'] = [{'bar': 'baz'}]
>>> print e.items()
[('foo', [{'bar': 'baz'}])]

Version:

>>> sys.version
'2.7.2+ (default, Jan 20 2012, 23:05:38) \n[GCC 4.6.2]'

臭虫还是臭虫?

编辑:更多相同,在 python 3.2 上:

>>> sys.version
'3.2.2rc1 (default, Aug 14 2011, 21:09:07) \n[GCC 4.6.1]'

>>> e['foo'] = [{'bar': 'baz'}]
>>> print(e.items())
[('foo', [{'bar': 'baz'}])]

>>> id(type(e['foo']))
137341152
>>> id(type([]))
137341152

>>> e['foo'].append({'asdf': 'fdsa'})
>>> print(e.items())
[('foo', [{'bar': 'baz'}])]

字典代理中的列表如何不包含附加元素?


这是一些非常有趣的行为,我不太确定它是如何工作的,但我会尝试一下为什么这种行为是这样的。

首先,请注意multiprocessing.Manager().dict()不是一个dict, 它是一个DictProxy object:

>>> d = multiprocessing.Manager().dict()
>>> d
<DictProxy object, typeid 'dict' at 0x7fa2bbe8ea50>

目的DictProxy课程是为了给你一个dict跨进程共享是安全的,这意味着它必须在正常的基础上实现一些锁定dict功能。

显然,这里实现的一部分是不允许您直接访问嵌套在 a 中的可变对象DictProxy,因为如果允许的话,您将能够以绕过所有锁定的方式修改您的共享对象DictProxy使用安全。

这里有一些证据表明您无法访问可变对象,这与发生的情况类似setdefault():

>>> d['foo'] = []
>>> foo = d['foo']
>>> id(d['foo'])
140336914055536
>>> id(foo)
140336914056184

使用普通字典,您会期望d['foo'] and foo指向同一个列表对象,对一个列表对象的修改将修改另一个。正如您所看到的,情况并非如此DictProxy类,因为多处理模块施加了额外的过程安全要求。

edit:以下注释来自多处理文档澄清了我上面想说的内容:


Note:对字典和列表代理中的可变值或项目的修改不会通过管理器传播,因为代理无法知道其值或项目何时被修改。要修改这样的项目,您可以将修改后的对象重新分配给容器代理:

# create a list proxy and append a mutable object (a dictionary)
lproxy = manager.list()
lproxy.append({})
# now mutate the dictionary
d = lproxy[0]
d['a'] = 1
d['b'] = 2
# at this point, the changes to d are not yet synced, but by
# reassigning the dictionary, the proxy is notified of the change
lproxy[0] = d

根据上述信息,以下是您如何重写原始代码以使用DictProxy:

# d.setdefault('foo', []).append({'bar': 'baz'})
d['foo'] = d.get('foo', []) + [{'bar': 'baz'}]

正如爱德华·洛珀在评论中建议的那样,编辑了上面的代码以使用 get() 代替 setdefault().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

multiprocessing.Manager().dict().setdefault() 是否损坏? 的相关文章