Issue #24400: Resurrect inspect.isawaitable()

collections.abc.Awaitable and collections.abc.Coroutine no longer
use __instancecheck__ hook to detect generator-based coroutines.

inspect.isawaitable() can be used to detect generator-based coroutines
and to distinguish them from regular generator objects.
This commit is contained in:
Yury Selivanov 2015-07-03 13:11:35 -04:00
parent 2ab5b092e5
commit fdbeb2b4b6
10 changed files with 92 additions and 39 deletions

View file

@ -162,10 +162,11 @@ ABC Inherits from Abstract Methods Mixin
:class:`~collections.abc.Coroutine` ABC are all instances of this ABC.
.. note::
In CPython, generator-based coroutines are *awaitables*, even though
they do not have an :meth:`__await__` method. This ABC
implements an :meth:`~class.__instancecheck__` method to make them
instances of itself.
In CPython, generator-based coroutines (generators decorated with
:func:`types.coroutine` or :func:`asyncio.coroutine`) are
*awaitables*, even though they do not have an :meth:`__await__` method.
Using ``isinstance(gencoro, Awaitable)`` for them will return ``False``.
Use :func:`inspect.isawaitable` to detect them.
.. versionadded:: 3.5
@ -179,10 +180,11 @@ ABC Inherits from Abstract Methods Mixin
:class:`Awaitable`. See also the definition of :term:`coroutine`.
.. note::
In CPython, generator-based coroutines are *awaitables* and *coroutines*,
even though they do not have an :meth:`__await__` method. This ABC
implements an :meth:`~class.__instancecheck__` method to make them
instances of itself.
In CPython, generator-based coroutines (generators decorated with
:func:`types.coroutine` or :func:`asyncio.coroutine`) are
*awaitables*, even though they do not have an :meth:`__await__` method.
Using ``isinstance(gencoro, Coroutine)`` for them will return ``False``.
Use :func:`inspect.isawaitable` to detect them.
.. versionadded:: 3.5

View file

@ -310,6 +310,25 @@ attributes:
.. versionadded:: 3.5
.. function:: isawaitable(object)
Return true if the object can be used in :keyword:`await` expression.
Can also be used to distinguish generator-based coroutines from regular
generators::
def gen():
yield
@types.coroutine
def gen_coro():
yield
assert not isawaitable(gen())
assert isawaitable(gen_coro())
.. versionadded:: 3.5
.. function:: istraceback(object)
Return true if the object is a traceback.

View file

@ -532,8 +532,9 @@ inspect
* New argument ``follow_wrapped`` for :func:`inspect.signature`.
(Contributed by Yury Selivanov in :issue:`20691`.)
* New :func:`~inspect.iscoroutine` and :func:`~inspect.iscoroutinefunction`
functions. (Contributed by Yury Selivanov in :issue:`24017`.)
* New :func:`~inspect.iscoroutine`, :func:`~inspect.iscoroutinefunction`
and :func:`~inspect.isawaitable` functions. (Contributed by
Yury Selivanov in :issue:`24017`.)
* New :func:`~inspect.getcoroutinelocals` and :func:`~inspect.getcoroutinestate`
functions. (Contributed by Yury Selivanov in :issue:`24400`.)