Json.dump a concurrent.futures.Future ()?

Let's say I have some futures:

f = concurrent.futures.Future() data = [f] 

And in the end, I want to dump them into JSON, and I guarantee that by this time the futures will be resolved:

 f.set_result(42) json.dumps(data) 

How can I marry two?

+5
source share
2 answers

Overriding the JSONEncoder class and calling o.result() in future instances is one way.

 class CustomJSONEncoder(json.JSONEncoder): def default(self, o, *args, **kwargs): if isinstance(o, concurrent.futures.Future): return o.result() return super(CustomJSONEncoder, self).default(o, *args, **kwargs) json.dumps(data, cls=CustomJSONEncoder) 

To make it work without a custom JSONEncoder, you can iterate through the data structure by calling o.result() :

 data = [o.result() if isinstance(o, concurrent.futures.Future) else o for o in data] 

Or change data in place:

 for i, o in enumerate(data): if isinstance(o, concurrent.futures.Future): data[i] = o.result() 
+4
source
 json.dumps([d.result() for d in data]) 
0
source

Source: https://habr.com/ru/post/1240921/


All Articles