Python中如何将类变量存储的类型作为同类方法参数的类型提示?
解决方案
要实现这个需求,你需要给Tool协议添加泛型参数,通过泛型关联类变量t的类型和f方法参数的类型。具体步骤如下:
- 导入
typing.Generic和TypeVar,定义一个类型变量来代表t的类型。 - 让
Tool协议继承Generic,并使用这个类型变量。 - 在协议中明确
t的类型为该类型变量,同时约束f方法的params参数为该类型。 - 实现类
Sum时,指定泛型参数,或者让类型检查器自动推断。
修改后的代码示例
from typing import Protocol, ClassVar, Any, Generic, TypeVar # 定义类型变量,代表类变量t的类型 T = TypeVar('T') class Tool(Protocol, Generic[T]): t: ClassVar[type[T]] # t是存储类型对象的类变量,类型为type[T] def f(self, params: T) -> Any: pass class Sum: t: ClassVar[type[list[int]]] = list[int] def f(self, params: list[int]) -> int: return sum(params) # 给use_tool添加泛型,让类型检查器能推断参数类型 def use_tool[T](tool: Tool[T], params: T) -> Any: return tool.f(params) # 扩展到Pydantic模型的场景 from pydantic import BaseModel class UserInput(BaseModel): a: int b: int class AddTool: t: ClassVar[type[UserInput]] = UserInput def f(self, params: UserInput) -> int: return params.a + params.b def use_tool_with_json[T](tool: Tool[T], json_str: str) -> Any: # 通过t的model_validate_json解析输入 params = tool.t.model_validate_json(json_str) return tool.f(params) s = Sum() print(use_tool(s, [1, 2])) # 类型检查通过 add_tool = AddTool() print(use_tool_with_json(add_tool, '{"a": 3, "b": 5}')) # 输出8,类型检查通过
关键说明
- 使用
TypeVar和Generic让Tool协议成为泛型协议,实现类型关联。 t的类型标注为type[T],表示t是一个能创建T类型实例的类型对象(比如list[int]是创建list[int]实例的类型)。use_tool函数也改为泛型函数,这样类型检查器能根据传入的Tool实例自动推断params的类型,确保类型安全。- 针对Pydantic场景,
tool.t可以直接调用model_validate_json等类方法,同时类型检查器能识别params的具体模型类型。
内容的提问来源于stack exchange,提问作者Tom Lin
相关产品推荐
相关产品推荐

