'yield from' inside async function Python

2019-09-20 09:49发布

问题:

SyntaxError: 'yield from' inside async function

async def handle(request):
    for m in (yield from request.post()):
        print(m)
    return web.Response()

Used python3.5 before, found pep525, install python3.6.5 and still receive this error.

回答1:

You are using the new async/await syntax to define and execute co-routines, but have not made a full switch. You need to use await here:

async def handle(request):
    post_data = await request.post()
    for m in post_data:
        print(m)
    return web.Response()

If you wanted to stick to the old, pre-Python 3.5 syntax, then mark your function as a coroutine with the @asyncio.coroutine decorator, drop the async keyword, and use yield from instead of await:

@async.coroutine
def handle(request):
    post_data = yield from request.post()
    for m in post_data:
        print(m)
    return web.Response()

but this syntax is being phased out, and is not nearly as discoverable and readable as the new syntax. You should only use this form if you need to write code that is compatible with older Python versions.