Python uses the Future object to callback other function sample code, pythonfuture

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.