Skip to content

Allow Return Statements with Values in Asynchronous Generators #125400

@alex-dixon

Description

@alex-dixon

Feature or enhancement

Proposal:

async def gen():
    yield 1
    yield 2
    return 3


async def runner():
    g = gen()
    while True:
        try:
            a = await g.__anext__()
            print("yielded", a)
        except StopAsyncIteration as e:
            print("returned", e.value)
            break


asyncio.run(runner())


# yielded 1
# yielded 2
# returned 3

The proposal adds optional return values to async generators.

This feature should be implemented to achieve syntactic and functional parity with synchronous generators.

Today:

def gen():
  yield 1
  yield 2
  return 3

async def agen():
  yield 1
  yield 2
  return 3 # Syntax error

Proposal:

def gen():
  yield 1
  yield 2
  return 3

async def agen():
  yield 1
  yield 2
  return 3

It can be implemented trivially in CPython as a nonbreaking change.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/allow-return-statements-with-values-in-asynchronous-generators/66886

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions