Skip to content
Advertisement

Unable to use dynamic classes with concurrent.futures.ProcessPoolExecutor

In the code below, I am dynamically creating an object of the class inside the _py attribute by using the generate_object method.

The code works perfectly if I am not using a concurrent approach. However, if I use concurrency from concurrent.futures, I do not get the desired result because of an error saying (beyond other things):

JavaScript

After googling this error, I understood that only picklable objects are to be passed as parameter in ProcessPoolExecutor.map(), so I decided to see how I could turn my dynamic class to be picklable.

The problem is that all other solutions for this problem creates a dynamic object in a different manner (different from what I’m using in _string_to_object()). Examples: 1 and 2

I would very much like to keep the dynamic object creation the way it is right now because a lot of my real code is based on it, therefore I am looking for a concurrent solution that works with this toy code below.

Code

JavaScript

Advertisement

Answer

I couldn’t come up with a way of getting the Script classes to be created in the global name space strictly adhering to your current scheme. However:

Since for each invocation of method generate_object you are creating a new class in the local namespace and instantiating an object of that class, why not postpone that work for it to be done in the process pool? This also has the added advantage of doing this class-creation processing in parallel and there is no pickling required. We now pass to concurrent_function the two integer arguments number_1 and number_2:

JavaScript

Prints:

JavaScript

A More Efficient Way

There is no need to use exec. Instead use closures:

JavaScript

Prints:

JavaScript

Using an Object Cache to Avoid Creating New Objects Unnecessarily

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