如何复用外部函数类型提示实现Mypy跨函数类型检查
实现函数参数类型自动同步与静态检查
核心思路
直接从目标函数(inner)的类型注解中提取参数类型,不用手动复制复杂类型提示;通过TypeAlias定义类型别名,确保后续inner类型更新时自动同步,同时让Mypy能正常对outer的参数x做类型校验。
基础解决方案代码
from typing import TypeAlias # 模拟外部库的inner函数(自带复杂类型提示) def inner(x: int) -> None: ... # 从inner的类型注解中提取x的类型,定义为可复用的类型别名 InnerXType: TypeAlias = inner.__annotations__["x"] # 定义outer函数,x参数直接用提取的类型 def outer(x: InnerXType, y: str) -> None: inner(x) # Mypy会抛出类型错误:Argument 1 to "outer" has incompatible type "str"; expected "int" outer(x="a", y="a")
进阶优化(更适配静态检查)
如果担心__annotations__的运行时特性影响静态检查,可以用typing.get_type_hints更安全地提取类型:
from typing import TypeAlias, get_type_hints def inner(x: int) -> None: ... # 通过get_type_hints规范提取inner的类型提示 inner_type_info = get_type_hints(inner) InnerXType: TypeAlias = inner_type_info["x"] def outer(x: InnerXType, y: str) -> None: inner(x) outer(x="a", y="a") # Mypy会触发类型错误提示
关键优势
- 完全避免手动复制
inner的复杂类型,减少维护成本 - 当外部库的
inner参数类型更新时,InnerXType会自动同步,无需修改代码 - Mypy等静态检查工具能正常识别提取的类型,精准校验
outer的参数合法性
内容的提问来源于stack exchange,提问作者Felix Zimmermann
相关产品推荐
相关产品推荐

