Вот упрощенный пример. :
Код: Выделить всё
from typing import Callable
class Operation[R]:
"""Encapsulates a function returning type R."""
def __init__(self, fn: Callable[[], R]) -> None:
self._fn = fn
def run(self) -> R:
return self._fn()
class OperationSequence[*Ts]:
"""
A typed-tuple container for Operation objects,
each possibly returning a different type in Ts.
For example, OperationSequence[int, str] means
item[0] returns int, item[1] returns str, etc.
"""
def __init__(self, *ops: Operation[*Ts]) -> None:
self._ops = ops # storing them in a tuple
def __getitem__(self, index: int) -> Operation[Ts[index]]: # What do do here?
return self._ops[index]
def __len__(self) -> int:
return len(self._ops)
def run_all(self) -> tuple[*Ts]:
# I'd like this to return e.g. tuple[int, str]
return tuple(op.run() for op in self._ops)
# Example usage
def get_number() -> int:
return 42
def get_text() -> str:
return "Hello"
ops = OperationSequence(
Operation(get_number), # returns int
Operation(get_text), # returns str
)
# I'd like mypy/pyright to infer:
# ops.run_all() -> tuple[int, str]
# ops[0].run() -> int
# ops[1].run() -> str
print(ops.run_all())
- *Конструктор: я получаю такие ошибки, как *“TypeVarTuple не является разрешено в этом контексте» в mypy/pyright.
- *getitem: я вижу * «Тип 'Operation[*Ts@OperationSequence]' не может быть назначен для возврата тип «Operation[Ts[index]]» или «TypeVar 'Ts@OperationSequence' не подлежит индексации» и т. д.
- run_all() возвращает полностью типизированный кортеж[*Ts],
- Каждый индекс имеет свой точный тип (например, ops[0] — это Operation[int]).
Подробнее здесь: https://stackoverflow.com/questions/793 ... n-python-3
Мобильная версия