Python Glossary Русский

Python 3.5+inspectfunction

inspect.isawaitable()

coroutines and generators

Checks whether an object can follow await: a coroutine, a Future, a Task, an object with __await__, or a @types.coroutine generator.

Syntax

inspect.isawaitable(object) -> bool

You check an object, not a function: isawaitable(asyncio.sleep) is False while isawaitable(asyncio.sleep(0)) is True. A plain generator cannot be awaited, but the same generator from a @types.coroutine function can, and this is how isawaitable tells them apart. The typical use is an API accepting both a sync and an async callback: result = cb(); if inspect.isawaitable(result): result = await result.

Examples

import asyncio, inspect
def sync_cb():
    return 'sync'
async def async_cb():
    return 'async'
async def call(cb):
    result = cb()
    if inspect.isawaitable(result):
        result = await result
    return result
print(asyncio.run(call(sync_cb)), asyncio.run(call(async_cb)))  # → sync async
print(inspect.isawaitable(asyncio.sleep))  # → False — функция, а не объект
import inspect, types
def gen():
    yield
@types.coroutine
def gen_coro():
    yield
print(inspect.isawaitable(gen()), inspect.isawaitable(gen_coro()))  # → False True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy