Debian Codegraph @

src/graphql/pyutils/is_awaitable.py

raw
1 import inspect
2 from typing import Any
3 from types import CoroutineType, GeneratorType
4
5 __all__ = ["is_awaitable"]
6
7 CO_ITERABLE_COROUTINE = inspect.CO_ITERABLE_COROUTINE
8
9
10 def is_awaitable(value: Any) -> bool:
11 """Return true if object can be passed to an ``await`` expression.
12
13 Instead of testing if the object is an instance of abc.Awaitable, it checks
14 the existence of an `__await__` attribute. This is much faster.
15 """
16 return (
17 # check for coroutine objects
18 isinstance(value, CoroutineType)
19 # check for old-style generator based coroutine objects
20 or isinstance(value, GeneratorType)
21 and bool(value.gi_code.co_flags & CO_ITERABLE_COROUTINE)
22 # check for other awaitables (e.g. futures)
23 or hasattr(value, "__await__")
24 )