blob: 08e94412b33b2315eca13744b16354572de134ad [file] [log] [blame]
Victor Stinnerf951d282014-06-29 00:46:45 +02001__all__ = ['coroutine',
2 'iscoroutinefunction', 'iscoroutine']
3
4import functools
5import inspect
Victor Stinnerb75380f2014-06-30 14:39:11 +02006import opcode
Victor Stinnerf951d282014-06-29 00:46:45 +02007import os
8import sys
9import traceback
Victor Stinnerb75380f2014-06-30 14:39:11 +020010import types
Victor Stinnerf951d282014-06-29 00:46:45 +020011
Victor Stinner71080fc2015-07-25 02:23:21 +020012from . import compat
Victor Stinnerf951d282014-06-29 00:46:45 +020013from . import events
Yury Selivanova0c1ba62016-10-28 12:52:37 -040014from . import base_futures
Victor Stinnerf951d282014-06-29 00:46:45 +020015from .log import logger
16
Victor Stinnerb75380f2014-06-30 14:39:11 +020017
18# Opcode of "yield from" instruction
19_YIELD_FROM = opcode.opmap['YIELD_FROM']
20
Victor Stinnerf951d282014-06-29 00:46:45 +020021# If you set _DEBUG to true, @coroutine will wrap the resulting
22# generator objects in a CoroWrapper instance (defined below). That
23# instance will log a message when the generator is never iterated
24# over, which may happen when you forget to use "yield from" with a
25# coroutine call. Note that the value of the _DEBUG flag is taken
26# when the decorator is used, so to be of any use it must be set
27# before you define your coroutines. A downside of using this feature
28# is that tracebacks show entries for the CoroWrapper.__next__ method
29# when _DEBUG is true.
Andrew Svetlovc07b16b2016-01-11 08:42:49 +020030_DEBUG = (not sys.flags.ignore_environment and
31 bool(os.environ.get('PYTHONASYNCIODEBUG')))
Victor Stinnerf951d282014-06-29 00:46:45 +020032
Victor Stinnerb75380f2014-06-30 14:39:11 +020033
Yury Selivanov1af2bf72015-05-11 22:27:25 -040034try:
Yury Selivanovdfbd27f2015-06-24 09:41:35 -040035 _types_coroutine = types.coroutine
Yury Selivanov0ed20cd2016-11-15 15:20:34 -050036 _types_CoroutineType = types.CoroutineType
Yury Selivanov1af2bf72015-05-11 22:27:25 -040037except AttributeError:
Yury Selivanov0ed20cd2016-11-15 15:20:34 -050038 # Python 3.4
Yury Selivanovdfbd27f2015-06-24 09:41:35 -040039 _types_coroutine = None
Yury Selivanov0ed20cd2016-11-15 15:20:34 -050040 _types_CoroutineType = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -040041
42try:
Yury Selivanovdfbd27f2015-06-24 09:41:35 -040043 _inspect_iscoroutinefunction = inspect.iscoroutinefunction
Yury Selivanov1af2bf72015-05-11 22:27:25 -040044except AttributeError:
Yury Selivanov0ed20cd2016-11-15 15:20:34 -050045 # Python 3.4
Yury Selivanovdfbd27f2015-06-24 09:41:35 -040046 _inspect_iscoroutinefunction = lambda func: False
Yury Selivanov1af2bf72015-05-11 22:27:25 -040047
48try:
Yury Selivanovdfbd27f2015-06-24 09:41:35 -040049 from collections.abc import Coroutine as _CoroutineABC, \
50 Awaitable as _AwaitableABC
Yury Selivanovc58cca52015-05-13 15:21:41 -040051except ImportError:
Yury Selivanovdfbd27f2015-06-24 09:41:35 -040052 _CoroutineABC = _AwaitableABC = None
Yury Selivanovc58cca52015-05-13 15:21:41 -040053
Yury Selivanov1af2bf72015-05-11 22:27:25 -040054
Victor Stinnerb75380f2014-06-30 14:39:11 +020055# Check for CPython issue #21209
56def has_yield_from_bug():
57 class MyGen:
58 def __init__(self):
59 self.send_args = None
60 def __iter__(self):
61 return self
62 def __next__(self):
63 return 42
64 def send(self, *what):
65 self.send_args = what
66 return None
67 def yield_from_gen(gen):
68 yield from gen
69 value = (1, 2, 3)
70 gen = MyGen()
71 coro = yield_from_gen(gen)
72 next(coro)
73 coro.send(value)
74 return gen.send_args != (value,)
75_YIELD_FROM_BUG = has_yield_from_bug()
76del has_yield_from_bug
77
78
Yury Selivanov1af2bf72015-05-11 22:27:25 -040079def debug_wrapper(gen):
80 # This function is called from 'sys.set_coroutine_wrapper'.
81 # We only wrap here coroutines defined via 'async def' syntax.
82 # Generator-based coroutines are wrapped in @coroutine
83 # decorator.
Yury Selivanovdfbd27f2015-06-24 09:41:35 -040084 return CoroWrapper(gen, None)
Yury Selivanov1af2bf72015-05-11 22:27:25 -040085
86
Victor Stinnerf951d282014-06-29 00:46:45 +020087class CoroWrapper:
Victor Stinnerc39ba7d2014-07-11 00:21:27 +020088 # Wrapper for coroutine object in _DEBUG mode.
Victor Stinnerf951d282014-06-29 00:46:45 +020089
Yury Selivanov1af2bf72015-05-11 22:27:25 -040090 def __init__(self, gen, func=None):
91 assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
Victor Stinnerf951d282014-06-29 00:46:45 +020092 self.gen = gen
Andrew Svetlovc07b16b2016-01-11 08:42:49 +020093 self.func = func # Used to unwrap @coroutine decorator
Victor Stinnerf951d282014-06-29 00:46:45 +020094 self._source_traceback = traceback.extract_stack(sys._getframe(1))
Yury Selivanov1af2bf72015-05-11 22:27:25 -040095 self.__name__ = getattr(gen, '__name__', None)
96 self.__qualname__ = getattr(gen, '__qualname__', None)
Victor Stinnera9acbe82014-07-05 15:29:41 +020097
98 def __repr__(self):
Victor Stinnerc39ba7d2014-07-11 00:21:27 +020099 coro_repr = _format_coroutine(self)
100 if self._source_traceback:
101 frame = self._source_traceback[-1]
102 coro_repr += ', created at %s:%s' % (frame[0], frame[1])
103 return '<%s %s>' % (self.__class__.__name__, coro_repr)
Victor Stinnerf951d282014-06-29 00:46:45 +0200104
105 def __iter__(self):
106 return self
107
108 def __next__(self):
Yury Selivanov70adad22015-05-31 21:37:09 -0400109 return self.gen.send(None)
Victor Stinnerf951d282014-06-29 00:46:45 +0200110
Victor Stinnerb75380f2014-06-30 14:39:11 +0200111 if _YIELD_FROM_BUG:
112 # For for CPython issue #21209: using "yield from" and a custom
113 # generator, generator.send(tuple) unpacks the tuple instead of passing
114 # the tuple unchanged. Check if the caller is a generator using "yield
115 # from" to decide if the parameter should be unpacked or not.
116 def send(self, *value):
117 frame = sys._getframe()
118 caller = frame.f_back
119 assert caller.f_lasti >= 0
120 if caller.f_code.co_code[caller.f_lasti] != _YIELD_FROM:
121 value = value[0]
122 return self.gen.send(value)
123 else:
124 def send(self, value):
125 return self.gen.send(value)
Victor Stinnerf951d282014-06-29 00:46:45 +0200126
Guido van Rossume3c65a72016-09-30 08:17:15 -0700127 def throw(self, type, value=None, traceback=None):
128 return self.gen.throw(type, value, traceback)
Victor Stinnerf951d282014-06-29 00:46:45 +0200129
130 def close(self):
131 return self.gen.close()
132
133 @property
134 def gi_frame(self):
135 return self.gen.gi_frame
136
137 @property
138 def gi_running(self):
139 return self.gen.gi_running
140
141 @property
142 def gi_code(self):
143 return self.gen.gi_code
144
Victor Stinner71080fc2015-07-25 02:23:21 +0200145 if compat.PY35:
Yury Selivanov29a602a2015-06-24 10:30:14 -0400146
Yury Selivanovb3dd6d72015-11-18 12:39:45 -0500147 def __await__(self):
148 cr_await = getattr(self.gen, 'cr_await', None)
149 if cr_await is not None:
150 raise RuntimeError(
151 "Cannot await on coroutine {!r} while it's "
152 "awaiting for {!r}".format(self.gen, cr_await))
153 return self
Yury Selivanov29a602a2015-06-24 10:30:14 -0400154
155 @property
Yury Selivanov09e60582015-07-03 00:41:16 -0400156 def gi_yieldfrom(self):
157 return self.gen.gi_yieldfrom
158
159 @property
160 def cr_await(self):
161 return self.gen.cr_await
162
163 @property
Yury Selivanov29a602a2015-06-24 10:30:14 -0400164 def cr_running(self):
165 return self.gen.cr_running
166
167 @property
168 def cr_code(self):
169 return self.gen.cr_code
170
171 @property
172 def cr_frame(self):
173 return self.gen.cr_frame
174
Victor Stinnerf951d282014-06-29 00:46:45 +0200175 def __del__(self):
176 # Be careful accessing self.gen.frame -- self.gen might not exist.
177 gen = getattr(self, 'gen', None)
178 frame = getattr(gen, 'gi_frame', None)
Yury Selivanov29a602a2015-06-24 10:30:14 -0400179 if frame is None:
180 frame = getattr(gen, 'cr_frame', None)
Victor Stinnerf951d282014-06-29 00:46:45 +0200181 if frame is not None and frame.f_lasti == -1:
Victor Stinner737c34f2014-07-11 01:04:16 +0200182 msg = '%r was never yielded from' % self
Victor Stinner2dba23a2014-07-03 00:59:00 +0200183 tb = getattr(self, '_source_traceback', ())
184 if tb:
185 tb = ''.join(traceback.format_list(tb))
186 msg += ('\nCoroutine object created at '
187 '(most recent call last):\n')
188 msg += tb.rstrip()
189 logger.error(msg)
Victor Stinnerf951d282014-06-29 00:46:45 +0200190
191
192def coroutine(func):
193 """Decorator to mark coroutines.
194
195 If the coroutine is not yielded from before it is destroyed,
196 an error message is logged.
197 """
Yury Selivanovdfbd27f2015-06-24 09:41:35 -0400198 if _inspect_iscoroutinefunction(func):
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400199 # In Python 3.5 that's all we need to do for coroutines
200 # defiend with "async def".
201 # Wrapping in CoroWrapper will happen via
202 # 'sys.set_coroutine_wrapper' function.
203 return func
204
Victor Stinnerf951d282014-06-29 00:46:45 +0200205 if inspect.isgeneratorfunction(func):
206 coro = func
207 else:
208 @functools.wraps(func)
209 def coro(*args, **kw):
210 res = func(*args, **kw)
Yury Selivanova0c1ba62016-10-28 12:52:37 -0400211 if (base_futures.isfuture(res) or inspect.isgenerator(res) or
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700212 isinstance(res, CoroWrapper)):
Victor Stinnerf951d282014-06-29 00:46:45 +0200213 res = yield from res
Yury Selivanovdfbd27f2015-06-24 09:41:35 -0400214 elif _AwaitableABC is not None:
Yury Selivanova3160852015-05-30 21:02:12 -0400215 # If 'func' returns an Awaitable (new in 3.5) we
216 # want to run it.
217 try:
218 await_meth = res.__await__
219 except AttributeError:
220 pass
221 else:
Yury Selivanovdfbd27f2015-06-24 09:41:35 -0400222 if isinstance(res, _AwaitableABC):
Yury Selivanova3160852015-05-30 21:02:12 -0400223 res = yield from await_meth()
Victor Stinnerf951d282014-06-29 00:46:45 +0200224 return res
225
226 if not _DEBUG:
Yury Selivanovdfbd27f2015-06-24 09:41:35 -0400227 if _types_coroutine is None:
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400228 wrapper = coro
Yury Selivanovdfbd27f2015-06-24 09:41:35 -0400229 else:
230 wrapper = _types_coroutine(coro)
Victor Stinnerf951d282014-06-29 00:46:45 +0200231 else:
232 @functools.wraps(func)
233 def wrapper(*args, **kwds):
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400234 w = CoroWrapper(coro(*args, **kwds), func=func)
Victor Stinnerf951d282014-06-29 00:46:45 +0200235 if w._source_traceback:
236 del w._source_traceback[-1]
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400237 # Python < 3.5 does not implement __qualname__
238 # on generator objects, so we set it manually.
239 # We use getattr as some callables (such as
240 # functools.partial may lack __qualname__).
241 w.__name__ = getattr(func, '__name__', None)
242 w.__qualname__ = getattr(func, '__qualname__', None)
Victor Stinnerf951d282014-06-29 00:46:45 +0200243 return w
244
Yury Selivanov0ed20cd2016-11-15 15:20:34 -0500245 wrapper._is_coroutine = _is_coroutine # For iscoroutinefunction().
Victor Stinnerf951d282014-06-29 00:46:45 +0200246 return wrapper
247
248
Yury Selivanov0ed20cd2016-11-15 15:20:34 -0500249# A marker for iscoroutinefunction.
250_is_coroutine = object()
251
252
Victor Stinnerf951d282014-06-29 00:46:45 +0200253def iscoroutinefunction(func):
254 """Return True if func is a decorated coroutine function."""
Yury Selivanov0ed20cd2016-11-15 15:20:34 -0500255 return (getattr(func, '_is_coroutine', None) is _is_coroutine or
Yury Selivanovdfbd27f2015-06-24 09:41:35 -0400256 _inspect_iscoroutinefunction(func))
Victor Stinnerf951d282014-06-29 00:46:45 +0200257
258
Victor Stinner1a870c92014-07-07 17:26:54 +0200259_COROUTINE_TYPES = (types.GeneratorType, CoroWrapper)
Yury Selivanovdfbd27f2015-06-24 09:41:35 -0400260if _CoroutineABC is not None:
261 _COROUTINE_TYPES += (_CoroutineABC,)
Yury Selivanov0ed20cd2016-11-15 15:20:34 -0500262if _types_CoroutineType is not None:
263 # Prioritize native coroutine check to speed-up
264 # asyncio.iscoroutine.
265 _COROUTINE_TYPES = (_types_CoroutineType,) + _COROUTINE_TYPES
Yury Selivanovc58cca52015-05-13 15:21:41 -0400266
Victor Stinnerb75380f2014-06-30 14:39:11 +0200267
Victor Stinnerf951d282014-06-29 00:46:45 +0200268def iscoroutine(obj):
269 """Return True if obj is a coroutine object."""
Victor Stinner1a870c92014-07-07 17:26:54 +0200270 return isinstance(obj, _COROUTINE_TYPES)
Victor Stinnerf951d282014-06-29 00:46:45 +0200271
272
273def _format_coroutine(coro):
274 assert iscoroutine(coro)
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700275
Yury Selivanov8dc3e432016-10-05 19:32:49 -0400276 if not hasattr(coro, 'cr_code') and not hasattr(coro, 'gi_code'):
Yury Selivanov6cc495e2016-11-08 19:16:01 -0500277 # Most likely a built-in type or a Cython coroutine.
278
279 # Built-in types might not have __qualname__ or __name__.
280 coro_name = getattr(
281 coro, '__qualname__',
282 getattr(coro, '__name__', type(coro).__name__))
Yury Selivanov8dc3e432016-10-05 19:32:49 -0400283 coro_name = '{}()'.format(coro_name)
284
285 running = False
286 try:
287 running = coro.cr_running
288 except AttributeError:
289 try:
290 running = coro.gi_running
291 except AttributeError:
292 pass
293
294 if running:
295 return '{} running'.format(coro_name)
296 else:
297 return coro_name
298
Yury Selivanov29a602a2015-06-24 10:30:14 -0400299 coro_name = None
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700300 if isinstance(coro, CoroWrapper):
301 func = coro.func
Yury Selivanov29a602a2015-06-24 10:30:14 -0400302 coro_name = coro.__qualname__
Yury Selivanov339d5e72015-06-24 10:45:44 -0400303 if coro_name is not None:
304 coro_name = '{}()'.format(coro_name)
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700305 else:
306 func = coro
Victor Stinnerf951d282014-06-29 00:46:45 +0200307
Yury Selivanov29a602a2015-06-24 10:30:14 -0400308 if coro_name is None:
Yury Selivanov45dccda2016-09-15 15:58:15 -0400309 coro_name = events._format_callback(func, (), {})
Yury Selivanov29a602a2015-06-24 10:30:14 -0400310
311 try:
312 coro_code = coro.gi_code
313 except AttributeError:
314 coro_code = coro.cr_code
315
316 try:
317 coro_frame = coro.gi_frame
318 except AttributeError:
319 coro_frame = coro.cr_frame
320
321 filename = coro_code.co_filename
Andrew Svetlovc07b16b2016-01-11 08:42:49 +0200322 lineno = 0
323 if (isinstance(coro, CoroWrapper) and
324 not inspect.isgeneratorfunction(coro.func) and
325 coro.func is not None):
326 source = events._get_function_source(coro.func)
327 if source is not None:
328 filename, lineno = source
Yury Selivanov29a602a2015-06-24 10:30:14 -0400329 if coro_frame is None:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700330 coro_repr = ('%s done, defined at %s:%s'
Victor Stinner15cc6782015-01-09 00:09:10 +0100331 % (coro_name, filename, lineno))
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200332 else:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700333 coro_repr = ('%s running, defined at %s:%s'
Victor Stinner15cc6782015-01-09 00:09:10 +0100334 % (coro_name, filename, lineno))
Yury Selivanov29a602a2015-06-24 10:30:14 -0400335 elif coro_frame is not None:
336 lineno = coro_frame.f_lineno
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700337 coro_repr = ('%s running at %s:%s'
Victor Stinner15cc6782015-01-09 00:09:10 +0100338 % (coro_name, filename, lineno))
Victor Stinnerf951d282014-06-29 00:46:45 +0200339 else:
Yury Selivanov29a602a2015-06-24 10:30:14 -0400340 lineno = coro_code.co_firstlineno
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700341 coro_repr = ('%s done, defined at %s:%s'
Victor Stinner15cc6782015-01-09 00:09:10 +0100342 % (coro_name, filename, lineno))
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200343
344 return coro_repr