Наследование и полиморфизм в Python при использовании mypy не работаетPython

Программы на Python
Anonymous
Наследование и полиморфизм в Python при использовании mypy не работает

Сообщение Anonymous »

Я хочу реализовать стандартный полиморфизм с помощью 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]:

Не работает с:
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

# Define T as contravariant
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]:
# Implementation here
pass


Подробнее здесь: https://stackoverflow.com/questions/787 ... ot-working

Вернуться в «Python»