Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question on typing Coroutines that return async generator "objects" #4461

Closed
ahnjaeshin opened this issue Aug 19, 2020 · 1 comment
Closed

Comments

@ahnjaeshin
Copy link

I have a question on adding types to a function that returns async_generator object
Here's a simple snippet that carries the issue.

async def gen() -> AsyncGenerator[int, None]:
    for idx in range(100):
        yield idx

async def func():
    await asyncio.sleep(1)
    return gen()

generator = await func()
async for idx in generator:
    print(idx)

In the snippet above, what would be the return type of func?
Setting as AsyncGenerator seems weird cause you need an await keyword to get the generator.
And setting as Awaitable[AsyncGenerator] is also weird, as func itself is already a coroutine.

The reason func returns a async_coroutine object and not just iterate through it (async def func(): async for idx in gen(): ...) is that I wanted to make sure await asyncio.sleep gets called when the generator is created.

@hauntsaninja
Copy link
Collaborator

hauntsaninja commented Aug 19, 2020

As it happens, also AsyncGenerator[int, None]! (Although, as in the sync world, you may wish to use AsyncIterator[int] in both cases)

See python/mypy#5070 and python/mypy#5385 for equivalent issues and explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants