multiprocessing.Manager()。dict()。setdefault()是否损坏?
问题内容:
其后期且可能是愚蠢的部门提出:
>>> import multiprocessing
>>> mgr = multiprocessing.Manager()
>>> d = mgr.dict()
>>> d.setdefault('foo', []).append({'bar': 'baz'})
>>> print d.items()
[('foo', [])] <-- Where did the dict go?
鉴于:
>>> e = mgr.dict()
>>> e['foo'] = [{'bar': 'baz'}]
>>> print e.items()
[('foo', [{'bar': 'baz'}])]
版:
>>> 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
对象:
>>> d = multiprocessing.Manager().dict()
>>> d
<DictProxy object, typeid 'dict' at 0x7fa2bbe8ea50>
DictProxy
该类的目的是为您提供一个dict
可以在进程之间共享的安全对象,这意味着它必须在常规dict
功能之上实现一些锁定。
显然,此处实现的一部分是不允许您直接访问嵌套在内的可变对象DictProxy
,因为如果允许,您将能够以绕过所有使DictProxy
安全使用的锁定的方式修改共享对象。
这是一些您无法访问可变对象的证据,这与发生的情况类似setdefault()
:
>>> d['foo'] = []
>>> foo = d['foo']
>>> id(d['foo'])
140336914055536
>>> id(foo)
140336914056184
使用普通字典,您会期望d['foo']
并foo
指向同一个列表对象,而对一个字典的修改会修改另一个。如您所见,DictProxy
由于多处理模块强加了额外的过程安全性要求,因此该类并非如此。
编辑:
以下来自多处理文档的注释阐明了我在上面试图说的内容:
注意:
对dict和list代理中的可变值或项的修改不会通过管理器传播,因为代理无法知道何时修改其值或项。要修改此类项目,可以将修改后的对象重新分配给容器代理:
# 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'}]
正如Edward Loper在评论中建议的那样,对以上代码进行了编辑,以 get()
代替 setdefault()
。