多处理.Manager()。dict()。setdefault()坏了吗?

时间:2012-05-29 22:31:36

标签: python multiprocessing

其迟到且非常可能是愚蠢的部门提出:

>>> 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]'

Bug还是wug?

编辑:更多相同的内容,在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'}])]

dict代理中的列表如何不包含其他元素?

3 个答案:

答案 0 :(得分:8)

这是一些非常有趣的行为,我不确定它是如何工作的,但我会理解为什么行为就是这样。

首先,请注意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类不是这种情况。

编辑multiprocessing documentation中的以下说明阐明了我上面要说的内容:


  

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

# 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()

答案 1 :(得分:2)

Manager()。dict()是一个DictProxy对象:

>>> mgr.dict()
<DictProxy object, typeid 'dict' at 0x1007bab50>
>>> type(mgr.dict())
<class 'multiprocessing.managers.DictProxy'>

DictProxy是BaseProxy类型的子类,它的行为与普通字典完全不同:http://docs.python.org/library/multiprocessing.html?highlight=multiprocessing#multiprocessing.managers.BaseProxy

所以,似乎你必须以不同于基础字典的方式处理mgr.dict()。

答案 2 :(得分:0)

items()返回一个副本。附加副本不会影响原件。 你是说这个吗?

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