如何在Python中检查模块是否实现指定函数并做类型校验?
在Python中检查模块是否符合特定函数签名
场景说明
有两个模块mod0和mod1,二者都实现了函数f和g,参数个数一致,但mod0中的g返回float类型,mod1中的g返回int类型。需要实现对模块的类型校验,让不符合签名要求的模块触发明确的错误提示。
模块代码示例
mod0/init.py
def f(a: int) -> int: return a def g(a: int) -> float: return float(a)
mod1/init.py
def f(a: int) -> int: return a def g(a: int) -> int: return a # 甚至是`g = f`?
初始尝试问题
你尝试用Protocol定义接口,但未触发预期的类型错误:
from typing import Protocol class ProtoFg(Protocol): @staticmethod def f(a: int) -> int: pass @staticmethod def g(a: int) -> float: pass def check_conformance(mod: ProtoFg): pass import mod0, mod1 check_conformance(mod0) check_conformance(mod1) # 期望此处触发报错,但未生效
解决方案:静态类型检查+正确的Protocol定义
Python运行时本身不做类型校验,必须借助mypy、pyright这类静态类型检查工具,同时修正Protocol的定义方式:
修正后的校验代码
from typing import Protocol, TypeVar # 模块是Python对象,Protocol中直接定义方法签名(self代表模块实例) class ProtoFg(Protocol): def f(self, a: int) -> int: ... def g(self, a: int) -> float: ... # 用TypeVar绑定Protocol,帮助类型检查器识别约束 ModType = TypeVar("ModType", bound=ProtoFg) def check_conformance(mod: ModType) -> None: pass import mod0, mod1 check_conformance(mod0) check_conformance(mod1) # 静态检查工具会在此处报错
执行静态检查后的错误提示
运行mypy type_checker.py会得到如下明确错误:
error: Argument 1 to "check_conformance" has incompatible type "module"; expected "ProtoFg" [arg-type]
note: "mod1.g" has incompatible return type "int"; expected "float"
完全符合你期望的提示效果,即使mod1中写的是g = f,类型检查工具也能检测到返回类型不匹配。
关键要点
- Protocol定义:模块作为Python对象,不需要用
@staticmethod修饰方法签名,直接以self指代模块实例。 - 依赖静态检查工具:Python运行时不会执行类型校验,必须使用
mypy或pyright才能触发错误提示。 - 兼容
g = f场景:类型检查工具会追踪变量的实际类型,即使函数是赋值得到的,也能检测到返回类型不匹配。
内容的提问来源于stack exchange,提问作者Samuel Marks
相关产品推荐
相关产品推荐

