Accessing an attribute of a multiprocessing Proxy of a class

后端 未结 4 651
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 03:14

I have a class that I want to share in a read-only fashion with children processes in a pool, so I prepared a proxy of a class but it didn\'t work. The following is a simpli

4条回答
  •  借酒劲吻你
    2020-12-03 04:04

    After spending few hours to reading the source codes, here is the simplest ways to implement the proxy class to expose all attributes and methods:

    class TestProxy(NamespaceProxy):
        _exposed_ = tuple(dir(Test))
    
        def __getattr__(self, name):
            result = super().__getattr__(name)
            if isinstance(result, types.MethodType):
                def wrapper(*args, **kwargs):
                    self._callmethod(name, args)
                return wrapper
            return result
    
    BaseManager.register('Test', Test, TestProxy)
    
    manager = BaseManager()
    test = manager.Test()
    

    Also, here is an auto proxy method:

    def Proxy(target):
        dic = {'types': types}
        exec('''def __getattr__(self, key):
            result = self._callmethod('__getattribute__', (key,))
            if isinstance(result, types.MethodType):
                def wrapper(*args, **kwargs):
                    self._callmethod(key, args)
                return wrapper
            return result''', dic)
        proxyName = target.__name__ + "Proxy"
        ProxyType = type(proxyName, (NamespaceProxy,), dic)
        ProxyType._exposed_ = tuple(dir(target))
        return ProxyType
    
    TestProxy = Proxy(Test)
    BaseManager.register('Test', Test, TestProxy)
    
    manager = BaseManager()
    test = manager.Test()
    
    

提交回复
热议问题