[英]python object composition and multiprocessing
如果我使用getattr实现对象组合并将该对象传递到新进程中,则会从getattr获得RecursionError。 这是一个例子:
from multiprocessing import Pool
class Bar:
def __init__(self, bar):
self.bar = bar
class Foo:
def __init__(self, bar):
self._bar = bar
def __getattr__(self, attr):
try:
return getattr(self._bar, attr)
except RecursionError:
print('RecursionError while trying to access {}'.format(attr))
raise AttributeError
def f(foo):
print(foo.bar)
if __name__ == '__main__':
foo = Foo(Bar('baz'))
f(foo)
p = Pool(1)
p.map(f, [foo])
输出是这样的:
baz
RecursionError while trying to access _bar
baz
Foo为什么找不到_bar属性,而不得不求助于getattr ?
问题在于,Python需要序列化foo
对象并在新进程中将其复活。 __init__
在复活过程中不会被调用,因此您的foo
对象不会足够早地具有._bar
属性。
解决的办法是让序列化/复活方法专门通过。 将您的__getattr__
更改为:
def __getattr__(self, attr):
if attr in {'__getstate__', '__setstate__'}:
return object.__getattr__(self, attr)
return getattr(self._bar, attr)
它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.