[英]How to access property attribute from multiprocess Proxy class in Python?
I am trying to get attribute from my Proxy class but I don't quite understand the implementation (as per https://docs.python.org/3.9/library/multiprocessing.html?highlight=multiprocessing#multiprocessing.managers.BaseManager.register )我正在尝试从我的代理 class 获取属性,但我不太了解实现(根据https://docs.python.org/3.9/library/multiprocessing.html?highlight=multiprocessing#multiprocessing.managers.BaseManager。注册)
I understand I need to pass exposed
and method_to_typeid
to the.register() method because if I don't I only have access to "public" methods and not attributes.我知道我需要将
exposed
和method_to_typeid
传递给 the.register() 方法,因为如果我不这样做,我只能访问“公共”方法而不是属性。
Here is my code;这是我的代码;
from multiprocessing import Process
from multiprocessing.managers import BaseManager
class CustomManager(BaseManager):
# nothing
pass
class TestClass:
def __init__(self):
self._items = []
@property
def items(self):
return self._items
def fill_items(self):
self._items.append(1)
if __name__ == "__main__":
CustomManager.register(
'TestClass',
TestClass,
exposed=('items', 'fill_items'),
method_to_typeid={'items': 'list'}
)
manager = CustomManager()
manager.start()
shared_object = manager.TestClass()
p = Process(target=shared_object.fill_items)
p.start()
p.join()
print(shared_object.items)
#print(shared_object.items())
I would expect this to return my list but it returns a reference to the method;我希望这会返回我的列表,但它会返回对该方法的引用;
Output: Output:
<bound method items of <AutoProxy[TestClass] object, typeid 'TestClass' at 0x7feb38056670>>
But when I try to call it as a method ie shared_object.items()
I get;但是当我尝试将它作为一种方法调用时,即
shared_object.items()
我得到了;
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/managers.py", line 824, in _callmethod
raise convert_to_error(kind, result)
TypeError: 'list' object is not callable
Which makes sense because it is an attribute that contains list
type value not a method.这是有道理的,因为它是一个包含
list
类型值而不是方法的属性。 So but then why when I try to call it as an attribute I get it's reference not the value?那么,为什么当我尝试将其作为属性调用时,我得到的是它的引用而不是值?
Tried following the official documentation and checked already asked questions, for most of which the solution was to add NamespaceProxy, but it looks like now instead of implementing our own NamespaceProxy the correct way is to just pass the two extra args for.register() method.尝试按照官方文档并检查已经提出的问题,其中大部分解决方案是添加 NamespaceProxy,但现在看起来不是实现我们自己的 NamespaceProxy,正确的方法是传递两个额外的参数 for.register() 方法.
The solution here is just to use threading
instead of multiprocessing
.这里的解决方案只是使用
threading
而不是multiprocessing
。 ChatGPT got pretty close to the implementation I needed but could not resolve the issue without changing the implementation of my classes. ChatGPT 非常接近我需要的实现,但如果不更改我的类的实现就无法解决问题。 In the end it makes more sense to use threads anyway because;
最后,无论如何使用线程更有意义,因为;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.