is_awaitable.py 798 B

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