使用mypy时Python继承与多态类型检查报错的解决方法
在mypy中实现多态特性的类型兼容问题
我希望在mypy中实现标准的多态特性,但此前从未使用过mypy,操作起来并不直观。
基类代码
class ContentPullOptions: pass class Tool(Protocol): async def pull_content(self, opts: ContentPullOptions) -> str | Dict[str, Any]: ...
子类代码
class GoogleSearchOptions(ContentPullOptions): query: str sites: List[str] class GoogleSearchTool(Tool): async def pull_content( self, opts: GoogleSearchOptions, ) -> str | Dict[str, Any]:
运行mypy时报错
error: Argument 1 of "pull_content" is incompatible with supertype "Tool"; supertype defines the argument type as "ContentPullOptions"
请问在mypy中进行此类基础继承类型检查,最易维护且简洁的实现方式是什么?我尝试过自定义类型、类型转换等方法,但都显得繁琐且不清晰。
解决方案
(该方案可能仍违反里氏替换原则)
from typing import TypeVar, Protocol, Dict, Any, List, Callable # 定义逆变类型变量T_contra T_contra = TypeVar('T_contra', bound=ContentPullOptions, contravariant=True) class ContentPullOptions: pass class Tool(Protocol[T_contra]): async def pull_content(self, opts: T_contra) -> str | Dict[str, Any]: ... class GoogleSearchOptions(ContentPullOptions): query: str sites: List[str] class GoogleSearchTool: async def pull_content( self, opts: GoogleSearchOptions, ) -> str | Dict[str, Any]: # 实现逻辑 pass
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

