![](/img/trans.png)
[英]Python multiprocessing.Manager dict containing value a list
[英]Is multiprocessing.Manager().dict().setdefault() broken?
其后期和非常可能是愚蠢的部门提出:
>>> 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'}])]
dict代理中的列表如何不包含其他元素?
这是一些非常有趣的行为,我不确定它是如何工作的,但我会解释为什么行为是这样的。
首先,请注意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和列表代理中的可变值或项的修改不会通过管理器传播,因为代理无法知道何时修改其值或项。 要修改此类项,可以将修改后的对象重新分配给容器代理:
# 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()
。
Manager()。dict()是一个DictProxy对象:
>>> mgr.dict()
<DictProxy object, typeid 'dict' at 0x1007bab50>
>>> type(mgr.dict())
<class 'multiprocessing.managers.DictProxy'>
DictProxy是BaseProxy类型的子类,它的行为完全不像普通的dict: http ://docs.python.org/library/multiprocessing.html?highlight = multipleprocessing #multiprocessing.managers.BaseProxy
因此,似乎你必须以不同于基础字典的方式处理mgr.dict()。
items()返回一个副本。 附加副本不会影响原件。 你的意思是?
>>> d['foo'] =({'bar': 'baz'})
>>> print d.items()
[('foo', {'bar': 'baz'})]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.