Skip to content

Better diagnostic to help users annotate async generator in stub #2875

Closed
astral-sh/ruff
#28692

Description

@niksabaldun

Summary

Consider the example:

from collections.abc import AsyncGenerator
import aiofiles

class AsyncTest:
    async def __call__(self, path: str) -> AsyncGenerator[str]:
        async with aiofiles.open(path) as f:
            async for line in f:
                yield line

async def test() -> None:
    test: AsyncTest = AsyncTest()
    items: list[str] = [item async for item in test('/')]

Ty does not complain about anything here, as it shouldn't. But if I replace the __call__ function with a stub:

class AsyncTest:
    async def __call__(self, path: str) -> AsyncGenerator[str]: ...

async def test() -> None:
    test: AsyncTest = AsyncTest()
    items: list[str] = [item async for item in test('/')]

Then, on the last line, ty reports an error: Object of type CoroutineType[Any, Any, AsyncGenerator[str, None]] is not async-iterable.

I assume that in the first case, ty can see the yield in the function body, so it infers that despite the async def, this is actually an async generator function.

But per PEP 525 / typing spec: if you annotate the return type of an async generator function, you should use AsyncGenerator[YieldType, SendType] as the return annotation, and the function is understood to be an async generator (not a coroutine returning one). Therefore, ty should be able to understand the function is an async generator even in the second example.

Version

0.0.17

Activity

  1. added
    async
    on Feb 21, 2026
  2. sharkdp commented on Feb 23, 2026

    @sharkdp
    Contributor

    I assume that in the first case, ty can see the yield in the function body, so it infers that despite the async def, this is actually an async generator function.

    Correct. That behavior is consistent with what other type checkers do.

    But per PEP 525 / typing spec: if you annotate the return type of an async generator function, you should use AsyncGenerator[YieldType, SendType] as the return annotation, and the function is understood to be an async generator (not a coroutine returning one). Therefore, ty should be able to understand the function is an async generator even in the second example.

    Where exactly did you see this in PEP 525 or the typing spec? I couldn't find that reference.

    There are some relevant discussions on discuss.python.org here: https://discuss.python.org/t/ambivalent-async-generator-function-signature/71439 https://discuss.python.org/t/overloads-of-async-generators-inconsistent-coroutine-wrapping/56665/12. Some discussed solutions are to omit the async of def __call__, or to add a dummy yield … body in the stub.

    mypy has documentation on this topic and a dedicated diagnostic. So it's reasonable to help ty users here as well.

  3. added
    documentation
    diagnostics
    on Feb 23, 2026
  4. added this to the Stable milestone on Feb 23, 2026
  5. niksabaldun commented on Feb 23, 2026

    @niksabaldun
    Author

    I have to apologize. I trusted Claude on this, but on further scrutiny it admitted that it "cited PEP 525 / typing spec with more confidence than was warranted". I should have been more thorough.

    So, the solution is to add a dummy yield to the stub. Closing the issue.

  6. sharkdp commented on Feb 23, 2026

    @sharkdp
    Contributor

    I see, thanks for the clarification.

    I think it's reasonable to leave this open though, given that it confuses both bots and humans (me included).

  7. lvndry commented on May 5, 2026

    @lvndry

    Hit this today with an abstract base class. Minimal repro:

    from abc import ABC, abstractmethod
    from collections.abc import AsyncGenerator, AsyncIterator
    
    class Base(ABC):
        @abstractmethod
        async def stream(self, data: AsyncIterator[bytes]) -> AsyncGenerator[str, None]: ...
    
    class Concrete(Base):
        async def stream(self, data: AsyncIterator[bytes]) -> AsyncGenerator[str, None]:
            yield "hello"

    ty 0.0.34 on the Concrete override:

    error[invalid-method-override]: `AsyncGenerator[str, None]` is not assignable to `CoroutineType[Any, Any, AsyncGenerator[str, None]]`
    error[not-iterable]: Object of type `CoroutineType[Any, Any, AsyncGenerator[str, None]]` is not async-iterable
    

    Workaround for now: declare the abstract method as def instead of async def. Works at runtime but misrepresents the contract to implementors.

  8. jonathandung commented on Jun 1, 2026

    @jonathandung
    Contributor

    Why does it misrepresent the contract? If I see an async def function, I would expect to have to await its return value. You can make a sync function that trivially combines some async generators and returns a new async generator; I do this often. There may also be legitimate cases where you would make an async function that returns an AsyncGenerator. For example:

    async def prime[T, R](agen: AsyncGenerator[T, R]) -> AsyncGenerator[T, R]:
        await agen.asend(None)` # "prime" an async generator into which you would send values
        # because a "just-started" async generator is not ready to accept non-None values
        return agen

    prime would return a coroutine resolving to an async generator, and if async def func() -> AsyncGenerator were to be unconditionally interpreted as sugar for def func() -> AsyncGenerator, the above case would require an even less idiomatic workaround (omitting the async def and annotating the return type as CoroutineType[Any, Any, AsyncGenerator[T, R]]).

    Of course, I am talking about .pyi files here, where there is no implementation. It should of course be acceptable (and desired!) that a concrete implementation using async def and yield in its body is inferred as returning an async generator, and not an awaitable of.

  9. changed the title [-]Properly recognize async generator functions[/-] [+]Better diagnostic to help users annotate async generator in stub[/+] on Jun 1, 2026
  10. carljm commented on Jun 1, 2026

    @carljm
    Contributor

    @lvndry I don't think using def over async def does misrepresent the contract -- for an async generator, the annotated return type fully describes the actual return type, and the async prefix keyword (when there is no body) is if anything the misleading part (since it suggests a possible wrapping in an awaitable, that doesn't actually occur at runtime for an async generator).

    In any case, as described in the mypy docs linked above, the two options here are "remove async " or "add a stub body with yield". Given the way these features have been specified to work, this is (perhaps unfortunately) just the state of things, and is true for all Python type checkers. So the only actionable item for ty here is to improve our diagnostics and documentation to recommend those two options.

  11. added
    stubs
    on Aug 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

asyncdiagnosticsdocumentationstubs

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions