Python如何标注函数参数与另一个函数一致?(重写库类方法场景)
关于提取方法关键字参数类型的语法实现
你设想的KwargsFrom这类语法确实存在,Python 3.12及以上版本的标准库typing模块中,新增的KwArgs类型构造器完全能满足需求——它可以直接提取任意函数或方法的关键字参数类型。
示例代码(Python 3.12+)
from typing import KwArgs from mail_library import MailClient class LocalMailClient(MailClient): def send(self, **kwargs: KwArgs[MailClient.send]) -> None: print(f'Mocking email to {kwargs["recipients"]}')
兼容低版本Python(3.8-3.11)
如果你的Python版本低于3.12,可以通过以下两种方式实现类似功能:
方式1:使用typing_extensions.KwArgs
先安装依赖库:
pip install typing_extensions
再编写代码:
from typing_extensions import KwArgs from mail_library import MailClient class LocalMailClient(MailClient): def send(self, **kwargs: KwArgs[MailClient.send]) -> None: print(f'Mocking email to {kwargs["recipients"]}')
方式2:使用ParamSpec
from typing import ParamSpec, TypeVar, Callable from mail_library import MailClient # 定义参数规范和返回值类型变量 P = ParamSpec('P') T = TypeVar('T') # 将MailClient.send的参数绑定到ParamSpec SendCallable: Callable[P, T] = MailClient.send class LocalMailClient(MailClient): def send(self, **kwargs: P.kwargs) -> None: print(f'Mocking email to {kwargs["recipients"]}')
以上方式都是针对静态类型检查器(比如mypy、pyright)设计的,能让类型检查工具识别关键字参数的类型,避免类型错误。
内容的提问来源于stack exchange,提问作者Mojimi
相关产品推荐
相关产品推荐

