如何针对TypedDict指定泛型?泛型类类型提示异常问题求解
解决泛型类中TypedDict关键字参数的类型提示问题
问题背景
要实现一个泛型类,包含两个核心成员:
- 函数
f:接收In类型的参数,加上Parameters定义的关键字参数 - 函数
make_parameters:返回可直接传入f的Parameters类型对象
当前代码存在类型提示错误:
- 无法将
Parameters类型变量绑定到TypedDict Unpack提示必须传入TypedDict类型
期望的使用方式如下:
def example_f(x: float, a: float, b: float) -> float: return a * x + b class ExampleParameters(TypedDict): a: float b: float f = Function[float, float, ExampleParameters](example_f, lambda: {"a": 1.0, "b": 2.0})
修复后的代码
from typing import TypeVar, Generic, Protocol, Callable, Tuple, TypedDict, Unpack In = TypeVar("In", contravariant=True) Out = TypeVar("Out", covariant=True) Parameters = TypeVar("Parameters", bound=TypedDict) class Function(Generic[In, Out, Parameters]): # 将内部协议改为泛型,关联类的三个泛型参数 class FProtocol(Protocol[In, Out, Parameters]): def __call__(self, x: In, **kwargs: Unpack[Parameters]) -> Out: ... def __init__( self, f: FProtocol[In, Out, Parameters], make_parameters: Callable[[], Parameters], ) -> None: self._f = f self._make_parameters = make_parameters def __call__(self, x: In) -> Tuple[Out, Parameters]: parameters = self._make_parameters() return self._f(x, **parameters), parameters
核心调整说明
- 泛型协议绑定:把原来的
FProtocol改成泛型协议,明确和类的In、Out、Parameters三个泛型参数关联,让类型检查器能准确识别Unpack操作的是合法的TypedDict类型,直接解决两个类型报错问题。 - 移除冗余代码:删掉了不必要的
super().__init__()调用,继承Generic的类无需显式调用父类构造函数。
验证效果
用你提供的示例代码测试,类型检查器现在能正确识别:
example_f的参数与ExampleParameters的键完全匹配make_parameters返回的字典符合ExampleParameters的类型要求- 调用
f(x)时,返回值会被正确推断为Tuple[float, ExampleParameters]
内容的提问来源于stack exchange,提问作者aurelia
相关产品推荐
相关产品推荐

