Issue #24400: Introduce a distinct type for 'async def' coroutines.

Summary of changes:

1. Coroutines now have a distinct, separate from generators
   type at the C level: PyGen_Type, and a new typedef PyCoroObject.
   PyCoroObject shares the initial segment of struct layout with
   PyGenObject, making it possible to reuse existing generators
   machinery.  The new type is exposed as 'types.CoroutineType'.

   As a consequence of having a new type, CO_GENERATOR flag is
   no longer applied to coroutines.

2. Having a separate type for coroutines made it possible to add
   an __await__ method to the type.  Although it is not used by the
   interpreter (see details on that below), it makes coroutines
   naturally (without using __instancecheck__) conform to
   collections.abc.Coroutine and collections.abc.Awaitable ABCs.

   [The __instancecheck__ is still used for generator-based
   coroutines, as we don't want to add __await__ for generators.]

3. Add new opcode: GET_YIELD_FROM_ITER.  The opcode is needed to
   allow passing native coroutines to the YIELD_FROM opcode.

   Before this change, 'yield from o' expression was compiled to:

      (o)
      GET_ITER
      LOAD_CONST
      YIELD_FROM

   Now, we use GET_YIELD_FROM_ITER instead of GET_ITER.

   The reason for adding a new opcode is that GET_ITER is used
   in some contexts (such as 'for .. in' loops) where passing
   a coroutine object is invalid.

4. Add two new introspection functions to the inspec module:
   getcoroutinestate(c) and getcoroutinelocals(c).

5. inspect.iscoroutine(o) is updated to test if 'o' is a native
   coroutine object.  Before this commit it used abc.Coroutine,
   and it was requested to update inspect.isgenerator(o) to use
   abc.Generator; it was decided, however, that inspect functions
   should really be tailored for checking for native types.

6. sys.set_coroutine_wrapper(w) API is updated to work with only
   native coroutines.  Since types.coroutine decorator supports
   any type of callables now, it would be confusing that it does
   not work for all types of coroutines.

7. Exceptions logic in generators C implementation was updated
   to raise clearer messages for coroutines:

   Before: TypeError("generator raised StopIteration")
   After: TypeError("coroutine raised StopIteration")
This commit is contained in:
Yury Selivanov 2015-06-22 12:19:30 -04:00
parent cd881b850c
commit 5376ba9630
29 changed files with 1014 additions and 378 deletions

View file

@ -34,30 +34,20 @@ _DEBUG = (not sys.flags.ignore_environment
try:
types.coroutine
_types_coroutine = types.coroutine
except AttributeError:
native_coroutine_support = False
else:
native_coroutine_support = True
_types_coroutine = None
try:
_iscoroutinefunction = inspect.iscoroutinefunction
_inspect_iscoroutinefunction = inspect.iscoroutinefunction
except AttributeError:
_iscoroutinefunction = lambda func: False
_inspect_iscoroutinefunction = lambda func: False
try:
inspect.CO_COROUTINE
except AttributeError:
_is_native_coro_code = lambda code: False
else:
_is_native_coro_code = lambda code: (code.co_flags &
inspect.CO_COROUTINE)
try:
from collections.abc import Coroutine as CoroutineABC, \
Awaitable as AwaitableABC
from collections.abc import Coroutine as _CoroutineABC, \
Awaitable as _AwaitableABC
except ImportError:
CoroutineABC = AwaitableABC = None
_CoroutineABC = _AwaitableABC = None
# Check for CPython issue #21209
@ -89,10 +79,7 @@ def debug_wrapper(gen):
# We only wrap here coroutines defined via 'async def' syntax.
# Generator-based coroutines are wrapped in @coroutine
# decorator.
if _is_native_coro_code(gen.gi_code):
return CoroWrapper(gen, None)
else:
return gen
return CoroWrapper(gen, None)
class CoroWrapper:
@ -177,8 +164,7 @@ def coroutine(func):
If the coroutine is not yielded from before it is destroyed,
an error message is logged.
"""
is_coroutine = _iscoroutinefunction(func)
if is_coroutine and _is_native_coro_code(func.__code__):
if _inspect_iscoroutinefunction(func):
# In Python 3.5 that's all we need to do for coroutines
# defiend with "async def".
# Wrapping in CoroWrapper will happen via
@ -193,7 +179,7 @@ def coroutine(func):
res = func(*args, **kw)
if isinstance(res, futures.Future) or inspect.isgenerator(res):
res = yield from res
elif AwaitableABC is not None:
elif _AwaitableABC is not None:
# If 'func' returns an Awaitable (new in 3.5) we
# want to run it.
try:
@ -201,15 +187,15 @@ def coroutine(func):
except AttributeError:
pass
else:
if isinstance(res, AwaitableABC):
if isinstance(res, _AwaitableABC):
res = yield from await_meth()
return res
if not _DEBUG:
if native_coroutine_support:
wrapper = types.coroutine(coro)
else:
if _types_coroutine is None:
wrapper = coro
else:
wrapper = _types_coroutine(coro)
else:
@functools.wraps(func)
def wrapper(*args, **kwds):
@ -231,12 +217,12 @@ def coroutine(func):
def iscoroutinefunction(func):
"""Return True if func is a decorated coroutine function."""
return (getattr(func, '_is_coroutine', False) or
_iscoroutinefunction(func))
_inspect_iscoroutinefunction(func))
_COROUTINE_TYPES = (types.GeneratorType, CoroWrapper)
if CoroutineABC is not None:
_COROUTINE_TYPES += (CoroutineABC,)
if _CoroutineABC is not None:
_COROUTINE_TYPES += (_CoroutineABC,)
def iscoroutine(obj):