diff options
author | Yury Selivanov <yselivanov@sprymix.com> | 2015-06-22 12:19:30 -0400 |
---|---|---|
committer | Yury Selivanov <yselivanov@sprymix.com> | 2015-06-22 12:19:30 -0400 |
commit | 5376ba9630e45ad177150ae68c9712640330a2fc (patch) | |
tree | 68eacabe0721f40098654fe5f2e0b0e3391d95c1 /Lib/types.py | |
parent | Fixed documentation of functions with const char* arguments. (diff) | |
download | cpython-5376ba9630e45ad177150ae68c9712640330a2fc.tar.gz cpython-5376ba9630e45ad177150ae68c9712640330a2fc.tar.bz2 cpython-5376ba9630e45ad177150ae68c9712640330a2fc.zip |
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")
Diffstat (limited to 'Lib/types.py')
-rw-r--r-- | Lib/types.py | 85 |
1 files changed, 52 insertions, 33 deletions
diff --git a/Lib/types.py b/Lib/types.py index 0a87c2f08e7..dc1b040f89e 100644 --- a/Lib/types.py +++ b/Lib/types.py @@ -19,6 +19,11 @@ def _g(): yield 1 GeneratorType = type(_g()) +async def _c(): pass +_c = _c() +CoroutineType = type(_c) +_c.close() # Prevent ResourceWarning + class _C: def _m(self): pass MethodType = type(_C()._m) @@ -40,7 +45,7 @@ except TypeError: GetSetDescriptorType = type(FunctionType.__code__) MemberDescriptorType = type(FunctionType.__globals__) -del sys, _f, _g, _C, # Not for export +del sys, _f, _g, _C, _c, # Not for export # Provide a PEP 3115 compliant mechanism for class creation @@ -164,29 +169,33 @@ import collections.abc as _collections_abc def coroutine(func): """Convert regular generator function to a coroutine.""" - # We don't want to import 'dis' or 'inspect' just for - # these constants. - CO_GENERATOR = 0x20 - CO_ITERABLE_COROUTINE = 0x100 - if not callable(func): raise TypeError('types.coroutine() expects a callable') - if (isinstance(func, FunctionType) and - isinstance(getattr(func, '__code__', None), CodeType) and - (func.__code__.co_flags & CO_GENERATOR)): - - # TODO: Implement this in C. - co = func.__code__ - func.__code__ = CodeType( - co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, - co.co_stacksize, - co.co_flags | CO_ITERABLE_COROUTINE, - co.co_code, - co.co_consts, co.co_names, co.co_varnames, co.co_filename, - co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, - co.co_cellvars) - return func + if (func.__class__ is FunctionType and + getattr(func, '__code__', None).__class__ is CodeType): + + co_flags = func.__code__.co_flags + + # Check if 'func' is a coroutine function. + # (0x180 == CO_COROUTINE | CO_ITERABLE_COROUTINE) + if co_flags & 0x180: + return func + + # Check if 'func' is a generator function. + # (0x20 == CO_GENERATOR) + if co_flags & 0x20: + # TODO: Implement this in C. + co = func.__code__ + func.__code__ = CodeType( + co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, + co.co_stacksize, + co.co_flags | 0x100, # 0x100 == CO_ITERABLE_COROUTINE + co.co_code, + co.co_consts, co.co_names, co.co_varnames, co.co_filename, + co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, + co.co_cellvars) + return func # The following code is primarily to support functions that # return generator-like objects (for instance generators @@ -195,11 +204,14 @@ def coroutine(func): class GeneratorWrapper: def __init__(self, gen): self.__wrapped__ = gen - self.send = gen.send - self.throw = gen.throw - self.close = gen.close self.__name__ = getattr(gen, '__name__', None) self.__qualname__ = getattr(gen, '__qualname__', None) + def send(self, val): + return self.__wrapped__.send(val) + def throw(self, *args): + return self.__wrapped__.throw(*args) + def close(self): + return self.__wrapped__.close() @property def gi_code(self): return self.__wrapped__.gi_code @@ -209,24 +221,31 @@ def coroutine(func): @property def gi_running(self): return self.__wrapped__.gi_running + cr_code = gi_code + cr_frame = gi_frame + cr_running = gi_running def __next__(self): return next(self.__wrapped__) def __iter__(self): return self.__wrapped__ - __await__ = __iter__ + def __await__(self): + return self.__wrapped__ @_functools.wraps(func) def wrapped(*args, **kwargs): coro = func(*args, **kwargs) - if coro.__class__ is GeneratorType: + if coro.__class__ is CoroutineType: + # 'coro' is a native coroutine object. + return coro + if (coro.__class__ is GeneratorType or + (isinstance(coro, _collections_abc.Generator) and + not isinstance(coro, _collections_abc.Coroutine))): + # 'coro' is either a pure Python generator iterator, or it + # implements collections.abc.Generator (and does not implement + # collections.abc.Coroutine). return GeneratorWrapper(coro) - # slow checks - if not isinstance(coro, _collections_abc.Coroutine): - if isinstance(coro, _collections_abc.Generator): - return GeneratorWrapper(coro) - raise TypeError( - 'callable wrapped with types.coroutine() returned ' - 'non-coroutine: {!r}'.format(coro)) + # 'coro' is either an instance of collections.abc.Coroutine or + # some other object -- pass it through. return coro return wrapped |