Код: Выделить всё
from typing import Protocol, List, Any
class MyProtocol(Protocol):
def __call__(self, docs: List[str], **kwargs: Any) -> str:
pass
def do_call(
mylist: List[str],
callback: MyProtocol,
**kwargs: Any,
) -> str:
return callback(mylist, **kwargs)
def my_func(mylist: List[str], **kwargs: Any) -> str:
return ",".join(mylist)
# this results in a warning
do_call(["a", "b", "c"], my_func)
Ожидаемый тип «MyProtocol», получено «(mylist: list[ str], kwargs: dict[str, Any]) -> вместо str'
Даже пример в документации Python приводит к предупреждению в строке это должно быть нормально.
Код: Выделить всё
from collections.abc import Iterable
from typing import Protocol
class Combiner(Protocol):
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...
def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
for item in data:
...
def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
...
def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
...
batch_proc([], good_cb) # OK
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
# different name and kind in the callback
Ожидаемый тип «Объединитель», получено «(vals: tuple[bytes, . ..], maxlen: int | None) -> list[bytes]' вместо этого
Есть ли способ сообщить подсказчику типа, что моя функция действительно «MyProtocol»? Правильна ли моя реализация или это может быть дефект встроенного подсказчика типов PyCharm?
Подробнее здесь: https://stackoverflow.com/questions/792 ... ith-kwargs