pytype icon indicating copy to clipboard operation
pytype copied to clipboard

Deduction error on the type of async function

Open ZHmao opened this issue 5 years ago • 1 comments

We have two example codes, they show the pytype unable to express async function correctly.

1 When check it with pytype, it will show this error:

Function bar was called with the wrong arguments [wrong-arg-types]
       Expected: (fun: Callable[[str], Awaitable[str]]) 
Actually passed: (fun: Callable[[str], str])
from typing import Callable, Awaitable


async def foo(a: str) -> str:
    return a


async def bar(fun: Callable[[str], Awaitable[str]]) -> str:
    return await fun('a')


async def go() -> None:
    await bar(foo)

We have tried with Union and Any, both of them can help us ignore this error.

2 This one, used Union, but another error happened:

in bar: bad option in return type [bad-return-type]
           Expected: Awaitable
  Actually returned: str
from typing import Callable, Awaitable, Union


async def foo(a: str) -> str:
    return a


class Bar:

    def __init__(self, fun: Callable[[str], Union[Awaitable[str], str]]) -> None:
        self.fun = fun

    async def bar(self) -> str:
        return await self.fun('a')


async def go() -> None:
    Bar(foo)

We have tried with Any, it worked.

ZHmao avatar Mar 09 '20 12:03 ZHmao

Thanks for the report. This happens because pytype treats foo as having type Callable[[str], str], when it should be wrapping the return type in Awaitable.

rchen152 avatar Mar 12 '20 03:03 rchen152

Is there any updates on fixing this issue? This is really fundamental feature of Python for giving functions or methods as parameters or returning callables from functions so these features not working in pytype for async def's really is a big disadvantage on selecting pytype when having async project. The workaround of using Any is not nice due really wanting to enforce strict as possible typing and also f.e. IDEs (like VS code) work much nicer when the typing is really correct.

makkesi avatar Apr 09 '24 13:04 makkesi