Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have some futures:

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

And eventually I want to dump these in JSON, and I guarantee that futures were resolved by that time:

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

How can I marry the two?

like image 468
Dima Tisnek Avatar asked Sep 26 '22 15:09

Dima Tisnek


1 Answers

Overriding the JSONEncoder class and calling o.result() on 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 could iterate through the data structure yourself, calling o.result():

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

Or modify data in place:

for i, o in enumerate(data):
    if isinstance(o, concurrent.futures.Future):
        data[i] = o.result()
like image 125
Seán Hayes Avatar answered Sep 28 '22 06:09

Seán Hayes