October 22, 2024
Chicago 12, Melborne City, USA
python

Python Protocol using keyword-only arguments requires implementation to have different signature


I’m on python 3.10.
Here is the protocol I defined:

class OnSubscribeFunc(Protocol):
    def __call__(self, instrument: str, *, send: Callable[[str], Coroutine]) -> AsyncGenerator:
        ...

When create a method that implements it like this:

    async def subscribe(self, instrument: str, *, send: Callable[[str], Coroutine]):
        yield ...

I get this warning: Expected type 'OnSubscribeFunc', got '(instrument: str, Any, send: (BaseModel) -> Coroutine) -> AsyncGenerator' instead

If I remove the * from my implementation however, the warning disappears. I would expect it to be the other way around because not having the * allows the implementation to have non-keyword-only arguments which might not be what I’m aiming for with my protocol.

So for comparison – this implementation gives no warning:

    async def subscribe(self, instrument: str, send: Callable[[str], Coroutine]):
        yield ...

This does not make any sense to me, why does it behave like this and is this expected or is it a bug in my type checker?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video