typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Awaitable.__await__ expects a Generator where an Iterator will do

Open wsanchez opened this issue 4 years ago • 3 comments

In Twisted, the Deferred class has set __await__ = __iter__, where __iter__ is typed thusly:

    def __iter__(self) -> "Deferred[_DeferredResultT]":

Deferred, insofar as it has an __iter__ method, is thus itself an Iterable. It also implements __next__, so is an Iterator.

Mypy is yielding this error:

src/twisted/internet/defer.py:919:17: error: Incompatible types in assignment (expression has type "Callable[[], Deferred[_DeferredResultT]]", base class "Awaitable" defined the type as
"Callable[[], Generator[Any, None, _DeferredResultT]]")  [assignment]

I suspect that perhaps Awaitable.__await__ could instead be more flexibly typed to return a Iterator[_T] instead of a Generator[Any, None, _T]… as that (a) seemingly works in this case and (b) the documentation for object.__await__ and PEP 492 say that it must return an iterator and not specifically a generator.


Deferred: mypy problem: https://github.com/python/typeshed/pull/5194#issuecomment-816339179

wsanchez avatar Mar 16 '21 22:03 wsanchez

Sounds reasonable to me. PR welcome!

srittau avatar Apr 08 '21 09:04 srittau

can we re-open this as the PR was reverted here: https://github.com/python/typeshed/pull/5195

graingert avatar Jul 13 '21 09:07 graingert

Looks like https://github.com/python/typeshed/pull/5194#issuecomment-816339179 is our best clue to how to address this in mypy (though maybe the mypy code has changed since I wrote that comment in 2021). If someone submits a PR to mypy fixing this, we can change typeshed afterwards.

JelleZijlstra avatar Mar 16 '24 13:03 JelleZijlstra