0

Consider this example from the Python documentation:

def gen(): # defines a generator function
  yield 123


async def agen(): # defines an asynchronous generator function
  yield 123

I know this example is simple, but what are things that I can do with gen and not with agen, and viceversa? In what way would I notice their difference?

Related:

I thought this question would help, but I I still don't get it: What are the differences between the purposes of generator functions and asynchronous generator functions

1 Answer 1

1

one fits into the async/await framework and the other doesn't.

first, regular generator func. no cooperative multitasking here:

def f():
    return 4


def g():
    return 5


def gen():
    """cannot call async functions here"""
    yield f()
    yield g()


def run():
    for v in gen():
        print(v)

vs the below, with cooperative multitasking. allows other tasks to run between after await/during async for

async def f():
    return 4


async def g():
    return 5


async def gen():
    """can await async functions here"""
    yield await f()
    yield await g()


async def run():
    async for v in gen():
        print(v)


asyncio.run(run())
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! QQ: Why I cannot call async functions in the first case but I can in the second case? Is that because only async functions can call async functions?
yep, that's right! in the first case you're not executing in the context of an event loop, so you can't "await" (i.e. uhh, pass control back to the event loop).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.