example.py:26: error: Argument 1 to "apply_operation" has incompatible type "Callable[[NamedArg(Any, 'x'), NamedArg(Any, 'y')], str]"; expected "Operation[str]"
example.py:28: error: Argument 1 to "apply_operation" has incompatible type "Callable[[DefaultNamedArg(Any, 'name')], str]"; expected "Operation[str]"
Found 2 errors in 1 file (checked 1 source file)
Что я делаю не так? Как мне сделать себя счастливым?
Как определить протокол Python для типа, который: [list] [*]вызывается [*]с любым количеством аргументы ключевых слов любого типа [*]которые возвращают значение указанного типа [/list] Это моя попытка: [code]from typing import Any, Protocol, TypeVar
T = TypeVar("T", covariant=True)
class Operation(Protocol[T]): def __call__(self, **kwargs: Any) -> T: pass
# some example functions that should be a structural sub-type of "Operation[str]" def sumint(*, x: Any, y: Any) -> str: return f"{x} + {y} = {x + y}"
# an example function that takes an "Operation[str]" as an argument def apply_operation(operation: Operation[str], **kwargs: Any) -> str: return operation(**kwargs)
if __name__ == "__main__": print(apply_operation(sumint, x=2, y=2)) # prints: 2 + 2 = 4 print(apply_operation(greet, name="Stack")) # prints: Hello Stack [/code] Однако mypy выдает ошибку: [code]example.py:26: error: Argument 1 to "apply_operation" has incompatible type "Callable[[NamedArg(Any, 'x'), NamedArg(Any, 'y')], str]"; expected "Operation[str]" example.py:28: error: Argument 1 to "apply_operation" has incompatible type "Callable[[DefaultNamedArg(Any, 'name')], str]"; expected "Operation[str]" Found 2 errors in 1 file (checked 1 source file) [/code] Что я делаю не так? Как мне сделать себя счастливым?