1

If I try running the following code in Python, I get the following error:

async def foo():
    yield 1

async def bar():
    x = await foo()
b=bar()
b.send(None)

TypeError: object async_generator can't be used in 'await' expression

On the other hand, the following code works (and throws a StopIteration, but this is expected):

async def foo():
    pass

async def bar():
    await foo()
b=bar()
b.send(None)

Why doesn't this work?

I can make it work if I replace foo with:

@coroutine
def foo():
    yield 1

The problem here is that this seems weird enough that I'm pretty sure this isn't the recommended way of getting this behaviour. Then in most languages you just need async and await, not @coroutine too!

1 Answer 1

1

I'm assuming here that you are using asyncio library.
I think that the use of the decorator @coroutine is suggested for compatibility reasons with async def functions,

although this is not strictly enforced.

asyncio.coroutine documentation

Also

@asyncio.coroutine Decorator to mark generator-based coroutines. This enables the generator use yield from to call async def coroutines, and also enables the generator to be called by async def coroutines, for instance using an await expression.

There is no need to decorate async def coroutines themselves.

Sign up to request clarification or add additional context in comments.

Comments

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.