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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With