Python类型提示:如何为作为参数的异步函数/类方法定义类型?
为异步函数/类方法参数添加类型提示的解决方案
要给作为参数的异步函数或类方法添加类型提示,需用到Python标准库typing中的相关类型:
核心类型说明
- 对于无参数的异步函数:
- 兼容Python 3.7+:使用
Callable[[], Coroutine[Any, Any, 返回值类型]],其中Coroutine的前两个泛型参数填Any即可(分别对应协程的发送类型和返回类型,大多数场景无需指定) - Python 3.10+简化写法:用新增的
AsyncCallable[[], 返回值类型]
- 兼容Python 3.7+:使用
- 对于无参数的同步函数:直接用
Callable[[], 返回值类型]
适配你的代码的修改示例
首先导入所需类型:
from typing import Callable, Coroutine, Any, list # Python 3.10+可替换为: # from typing import AsyncCallable, list
修改后的函数定义:
async def get_mails(api: SomeApi, all_contacts: ContactDict, query_function: Callable[[], Coroutine[Any, Any, list[str]]], aggregate_function: Callable[[], list]) -> list: customer_emails = await query_function() for customer_email in customer_emails: for email in await get_emails_by_customer(api, customer_email, get_employees()): all_contacts[customer_email].add_mail(email) return aggregate_function()
如果使用Python 3.10+,query_function的类型可以简化为:
query_function: AsyncCallable[[], list[str]]
关于类方法的补充
如果传入的是类方法,只要你传递的是绑定到实例的方法(比如obj.query_method而非Class.query_method),方法签名会自动忽略self参数,直接使用上述类型提示即可匹配。
内容的提问来源于stack exchange,提问作者Jeroen Vermunt
相关产品推荐
相关产品推荐

