Python Future对象实现函数回调的示例解析

程一诺
程一诺
发布时间:2026-10-13| 3人浏览过
原创

本文介绍Python中利用Future对象实现函数回调的方法。通过add_done_callback注册回调,结合functools.partial处理多参数,在set_result设置结果时触发回调执行。示例展示了如何在异步编程中注册并触发回调函数,适用于需要结果通知的场景。

前言

本文主要介绍Python中利用Future对象进行函数回调的相关内容,供读者参考学习。接下来将详细展开具体实现方式。

Future对象在设置完成结果后,可以像协程一样立即触发回调其他函数的操作。

具体示例如下:

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() 

运行输出结果如下:

registering callbacks on future
setting result of future
1: future done: the result
2: future done: the result

在该示例中,首先调用函数add_done_callback()来注册一个回调函数。由于该回调仅支持单个参数,因此使用functools.partial进行封装处理。当set_result()函数被调用后,回调函数将立即执行。

总结

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助。如果有疑问,欢迎留言交流,感谢大家对本站的支持。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。