Python multiprocessing Manager with @property obje

2019-08-23 03:45发布

I have a fairly complex object I need to share access to across processes in Python. It has a few @property methods/attributes on it which the AutoProxy doesn't seem to process. How can I expose these through the manager?

from multiprocessing.managers import BaseManager

class Foo(object):

    def __init__(self, a):
        self._a = a

    @property
    def a(self):
        return self._a

class FooManager(BaseManager): pass

FooManager.register("Foo", Foo)

if __name__ == "__main__":
    fmgr = FooManager()
    fmgr.start()
    foo = fmgr.Foo(5)
    # Below causes error
    foo.a

And the error I get is:

Traceback (most recent call last): File "test.py", line 26, in foo.a AttributeError: 'AutoProxy[Foo]' object has no attribute 'a'

EDIT

So as mentioned in the comments below, one approach is to also define this:

class FooProxy(NamespaceProxy):
    _exposed_ = ('__getattribute__', '__setattr__', '__delattr__', 'a')

And register the Foo object as:

FooManager.register("Foo", Foo, FooProxy)

While this seems to work fine if anyone knows a more automatic process to incorporate any and all @property objects that would be terrific.

0条回答
登录 后发表回答