Код: Выделить всё
from typing import Protocol, TypeVar, Generic
TIn = TypeVar('TIn', contravariant=True)
TOut = TypeVar('TOut', covariant=True)
class Decorator(Protocol, Generic[TIn, TOut]):
"""
Represents a decorated value, used to simplify type definitions
"""
def __call__(self, value: TIn) -> TOut:
...
Код: Выделить всё
IntFunction = Callable[[int, int], int]
def register_operator(op: str) -> Decorator[IntFunction, IntFunction]:
def inner(value: IntFunction) -> IntFunction:
# register the function or whatever
return value
return inner
@register_operator("+")
def add(a: int, b: int) -> int:
return a + b
Это полезно для декораторов, преобразующих тип (например, преобразующих его из IntFunction в StrFunction), но почти во всех случаях TIn идентичен TOut, поэтому я хочу упростить использование моего определения.
По сути, я хочу сделать так, чтобы, если TOut не задан, предполагалось, что быть таким же, как TIn, что позволит упростить приведенную выше функцию декоратора до
Код: Выделить всё
def register_operator(op: str) -> Decorator[IntFunction]:
# Simplification here ^
def inner(value: IntFunction) -> IntFunction:
# register the function or whatever
return value
return inner
Код: Выделить всё
class Decorator(Protocol, Generic[TIn, TOut = TIn]):
"""
Represents a decorated value, used to simplify type definitions
"""
def __call__(self, value: TIn) -> TOut:
...
Как мне реализовать эту функциональность, сохраняя при этом уверенность, которую предоставляет Mypy? Я рад сделать определение Decorator настолько сложным, насколько это необходимо, но я хочу сохранить его простое использование.
Подробнее здесь: https://stackoverflow.com/questions/775 ... -in-python