Python Glossary Русский

Python 3.4+until 3.11Async programmingfunction

@asyncio.coroutine

removed

Decorator that turned a generator using yield from into an asyncio coroutine. Removed in Python 3.11; write async def and await.

Syntax

@asyncio.coroutine  # до 3.11

Before async/await syntax (Python 3.5) asyncio coroutines were generators: the function was marked @asyncio.coroutine and awaited with yield from. Once async def existed the decorator stayed for compatibility, was deprecated in 3.8 and removed in 3.11. How to rewrite: drop the decorator, change def to async def, and replace every yield from with await. Run the top coroutine with asyncio.run(main()) instead of loop.run_until_complete().

Examples

# Python 3.11+
import asyncio
try:
    asyncio.coroutine
except AttributeError as e:
    print(type(e).__name__)  # → AttributeError
# Python 3.11+
import asyncio
async def answer():
    await asyncio.sleep(0)
    return 42
print(asyncio.run(answer()))  # → 42
import asyncio
@asyncio.coroutine
def answer():
    yield from asyncio.sleep(0)
    return 42
loop = asyncio.new_event_loop()
print(loop.run_until_complete(answer()))  # → 42
loop.close()

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy