Python uses the Future object to callback other function sample code, pythonfuture
Preface
This article describes how to use a Future object to call back other functions in python. I will share the content for your reference. I will not talk about it here. Let's take a look at the details.
The Future object can also be called back to other functions immediately when the result is set like a coroutine.
Example:
import asyncio import functools def callback(future, n): print('{}: future done: {}'.format(n, future.result())) async def register_callbacks(all_done): print('registering callbacks on future') all_done.add_done_callback(functools.partial(callback, n=1)) all_done.add_done_callback(functools.partial(callback, n=2)) async def main(all_done): await register_callbacks(all_done) print('setting result of future') all_done.set_result('the result') event_loop = asyncio.get_event_loop() try: all_done = asyncio.Future() event_loop.run_until_complete(main(all_done)) finally: event_loop.close()
The output result is as follows:
registering callbacks on futuresetting result of future1: future done: the result2: future done: the result
In this example, call the Functionadd_done_callback()To register a callback function. Because only one parameter is supportedfunctools.partialFor encapsulation. Whenset_result()After the function is called, The callback function is executed immediately.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.