Skip to content
Advertisement

Accessing an attribute of a multiprocessing Proxy of a class

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 simplified example of my problem.

JavaScript

When I run this code I get:

JavaScript

It seems that I cannot access the attribute of a shared object directly via a proxy. Is the only way using a method that gets the attribute, or am I doing something wrong?

Advertisement

Answer

The Proxy objects used by multiprocessing.BaseManager and its sub-classes normally only expose methods from the objects they’re referring to, not attributes. Now, there is multiprocessing.Manager().Namespace, which provides a Proxy sub-class that does provide access to attributes, rather than methods. We can create our own Proxy type which inherits from that, which enables access to all our attributes, as well as access to our b function:

JavaScript

Output:

JavaScript

Edit:

If you want to be able to dynamically add methods from your original class to a Proxy class, you can do something like this:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement