Python Glossary Русский

Python 3.5+typesfunction

types.coroutine()

generators and coroutines

A decorator that turns a generator function into a generator-based coroutine: its result can be awaited inside async def.

Syntax

@types.coroutine
def gen_func(): ...

It bridges old yield-based coroutines and modern async def — this is exactly how asyncio.sleep(0) works: a bare yield hands control to the event loop. The returned object stays a generator, not a CoroutineType, so an isinstance check against CoroutineType will not recognise it. New code does not need it: the old @asyncio.coroutine was removed in 3.11, and for your own awaitables defining __await__ is simpler.

Examples

import asyncio
import types
@types.coroutine
def pause():
    yield
async def main():
    await pause()
    return 'done'
print(asyncio.run(main()))  # → done
print(isinstance(pause(), types.GeneratorType))  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy