1 | n/a | __all__ = ['coroutine', |
---|
2 | n/a | 'iscoroutinefunction', 'iscoroutine'] |
---|
3 | n/a | |
---|
4 | n/a | import functools |
---|
5 | n/a | import inspect |
---|
6 | n/a | import opcode |
---|
7 | n/a | import os |
---|
8 | n/a | import sys |
---|
9 | n/a | import traceback |
---|
10 | n/a | import types |
---|
11 | n/a | |
---|
12 | n/a | from . import compat |
---|
13 | n/a | from . import events |
---|
14 | n/a | from . import base_futures |
---|
15 | n/a | from .log import logger |
---|
16 | n/a | |
---|
17 | n/a | |
---|
18 | n/a | # Opcode of "yield from" instruction |
---|
19 | n/a | _YIELD_FROM = opcode.opmap['YIELD_FROM'] |
---|
20 | n/a | |
---|
21 | n/a | # If you set _DEBUG to true, @coroutine will wrap the resulting |
---|
22 | n/a | # generator objects in a CoroWrapper instance (defined below). That |
---|
23 | n/a | # instance will log a message when the generator is never iterated |
---|
24 | n/a | # over, which may happen when you forget to use "yield from" with a |
---|
25 | n/a | # coroutine call. Note that the value of the _DEBUG flag is taken |
---|
26 | n/a | # when the decorator is used, so to be of any use it must be set |
---|
27 | n/a | # before you define your coroutines. A downside of using this feature |
---|
28 | n/a | # is that tracebacks show entries for the CoroWrapper.__next__ method |
---|
29 | n/a | # when _DEBUG is true. |
---|
30 | n/a | _DEBUG = (not sys.flags.ignore_environment and |
---|
31 | n/a | bool(os.environ.get('PYTHONASYNCIODEBUG'))) |
---|
32 | n/a | |
---|
33 | n/a | |
---|
34 | n/a | try: |
---|
35 | n/a | _types_coroutine = types.coroutine |
---|
36 | n/a | _types_CoroutineType = types.CoroutineType |
---|
37 | n/a | except AttributeError: |
---|
38 | n/a | # Python 3.4 |
---|
39 | n/a | _types_coroutine = None |
---|
40 | n/a | _types_CoroutineType = None |
---|
41 | n/a | |
---|
42 | n/a | try: |
---|
43 | n/a | _inspect_iscoroutinefunction = inspect.iscoroutinefunction |
---|
44 | n/a | except AttributeError: |
---|
45 | n/a | # Python 3.4 |
---|
46 | n/a | _inspect_iscoroutinefunction = lambda func: False |
---|
47 | n/a | |
---|
48 | n/a | try: |
---|
49 | n/a | from collections.abc import Coroutine as _CoroutineABC, \ |
---|
50 | n/a | Awaitable as _AwaitableABC |
---|
51 | n/a | except ImportError: |
---|
52 | n/a | _CoroutineABC = _AwaitableABC = None |
---|
53 | n/a | |
---|
54 | n/a | |
---|
55 | n/a | # Check for CPython issue #21209 |
---|
56 | n/a | def has_yield_from_bug(): |
---|
57 | n/a | class MyGen: |
---|
58 | n/a | def __init__(self): |
---|
59 | n/a | self.send_args = None |
---|
60 | n/a | def __iter__(self): |
---|
61 | n/a | return self |
---|
62 | n/a | def __next__(self): |
---|
63 | n/a | return 42 |
---|
64 | n/a | def send(self, *what): |
---|
65 | n/a | self.send_args = what |
---|
66 | n/a | return None |
---|
67 | n/a | def yield_from_gen(gen): |
---|
68 | n/a | yield from gen |
---|
69 | n/a | value = (1, 2, 3) |
---|
70 | n/a | gen = MyGen() |
---|
71 | n/a | coro = yield_from_gen(gen) |
---|
72 | n/a | next(coro) |
---|
73 | n/a | coro.send(value) |
---|
74 | n/a | return gen.send_args != (value,) |
---|
75 | n/a | _YIELD_FROM_BUG = has_yield_from_bug() |
---|
76 | n/a | del has_yield_from_bug |
---|
77 | n/a | |
---|
78 | n/a | |
---|
79 | n/a | def debug_wrapper(gen): |
---|
80 | n/a | # This function is called from 'sys.set_coroutine_wrapper'. |
---|
81 | n/a | # We only wrap here coroutines defined via 'async def' syntax. |
---|
82 | n/a | # Generator-based coroutines are wrapped in @coroutine |
---|
83 | n/a | # decorator. |
---|
84 | n/a | return CoroWrapper(gen, None) |
---|
85 | n/a | |
---|
86 | n/a | |
---|
87 | n/a | class CoroWrapper: |
---|
88 | n/a | # Wrapper for coroutine object in _DEBUG mode. |
---|
89 | n/a | |
---|
90 | n/a | def __init__(self, gen, func=None): |
---|
91 | n/a | assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen |
---|
92 | n/a | self.gen = gen |
---|
93 | n/a | self.func = func # Used to unwrap @coroutine decorator |
---|
94 | n/a | self._source_traceback = traceback.extract_stack(sys._getframe(1)) |
---|
95 | n/a | self.__name__ = getattr(gen, '__name__', None) |
---|
96 | n/a | self.__qualname__ = getattr(gen, '__qualname__', None) |
---|
97 | n/a | |
---|
98 | n/a | def __repr__(self): |
---|
99 | n/a | coro_repr = _format_coroutine(self) |
---|
100 | n/a | if self._source_traceback: |
---|
101 | n/a | frame = self._source_traceback[-1] |
---|
102 | n/a | coro_repr += ', created at %s:%s' % (frame[0], frame[1]) |
---|
103 | n/a | return '<%s %s>' % (self.__class__.__name__, coro_repr) |
---|
104 | n/a | |
---|
105 | n/a | def __iter__(self): |
---|
106 | n/a | return self |
---|
107 | n/a | |
---|
108 | n/a | def __next__(self): |
---|
109 | n/a | return self.gen.send(None) |
---|
110 | n/a | |
---|
111 | n/a | if _YIELD_FROM_BUG: |
---|
112 | n/a | # For for CPython issue #21209: using "yield from" and a custom |
---|
113 | n/a | # generator, generator.send(tuple) unpacks the tuple instead of passing |
---|
114 | n/a | # the tuple unchanged. Check if the caller is a generator using "yield |
---|
115 | n/a | # from" to decide if the parameter should be unpacked or not. |
---|
116 | n/a | def send(self, *value): |
---|
117 | n/a | frame = sys._getframe() |
---|
118 | n/a | caller = frame.f_back |
---|
119 | n/a | assert caller.f_lasti >= 0 |
---|
120 | n/a | if caller.f_code.co_code[caller.f_lasti] != _YIELD_FROM: |
---|
121 | n/a | value = value[0] |
---|
122 | n/a | return self.gen.send(value) |
---|
123 | n/a | else: |
---|
124 | n/a | def send(self, value): |
---|
125 | n/a | return self.gen.send(value) |
---|
126 | n/a | |
---|
127 | n/a | def throw(self, type, value=None, traceback=None): |
---|
128 | n/a | return self.gen.throw(type, value, traceback) |
---|
129 | n/a | |
---|
130 | n/a | def close(self): |
---|
131 | n/a | return self.gen.close() |
---|
132 | n/a | |
---|
133 | n/a | @property |
---|
134 | n/a | def gi_frame(self): |
---|
135 | n/a | return self.gen.gi_frame |
---|
136 | n/a | |
---|
137 | n/a | @property |
---|
138 | n/a | def gi_running(self): |
---|
139 | n/a | return self.gen.gi_running |
---|
140 | n/a | |
---|
141 | n/a | @property |
---|
142 | n/a | def gi_code(self): |
---|
143 | n/a | return self.gen.gi_code |
---|
144 | n/a | |
---|
145 | n/a | if compat.PY35: |
---|
146 | n/a | |
---|
147 | n/a | def __await__(self): |
---|
148 | n/a | cr_await = getattr(self.gen, 'cr_await', None) |
---|
149 | n/a | if cr_await is not None: |
---|
150 | n/a | raise RuntimeError( |
---|
151 | n/a | "Cannot await on coroutine {!r} while it's " |
---|
152 | n/a | "awaiting for {!r}".format(self.gen, cr_await)) |
---|
153 | n/a | return self |
---|
154 | n/a | |
---|
155 | n/a | @property |
---|
156 | n/a | def gi_yieldfrom(self): |
---|
157 | n/a | return self.gen.gi_yieldfrom |
---|
158 | n/a | |
---|
159 | n/a | @property |
---|
160 | n/a | def cr_await(self): |
---|
161 | n/a | return self.gen.cr_await |
---|
162 | n/a | |
---|
163 | n/a | @property |
---|
164 | n/a | def cr_running(self): |
---|
165 | n/a | return self.gen.cr_running |
---|
166 | n/a | |
---|
167 | n/a | @property |
---|
168 | n/a | def cr_code(self): |
---|
169 | n/a | return self.gen.cr_code |
---|
170 | n/a | |
---|
171 | n/a | @property |
---|
172 | n/a | def cr_frame(self): |
---|
173 | n/a | return self.gen.cr_frame |
---|
174 | n/a | |
---|
175 | n/a | def __del__(self): |
---|
176 | n/a | # Be careful accessing self.gen.frame -- self.gen might not exist. |
---|
177 | n/a | gen = getattr(self, 'gen', None) |
---|
178 | n/a | frame = getattr(gen, 'gi_frame', None) |
---|
179 | n/a | if frame is None: |
---|
180 | n/a | frame = getattr(gen, 'cr_frame', None) |
---|
181 | n/a | if frame is not None and frame.f_lasti == -1: |
---|
182 | n/a | msg = '%r was never yielded from' % self |
---|
183 | n/a | tb = getattr(self, '_source_traceback', ()) |
---|
184 | n/a | if tb: |
---|
185 | n/a | tb = ''.join(traceback.format_list(tb)) |
---|
186 | n/a | msg += ('\nCoroutine object created at ' |
---|
187 | n/a | '(most recent call last):\n') |
---|
188 | n/a | msg += tb.rstrip() |
---|
189 | n/a | logger.error(msg) |
---|
190 | n/a | |
---|
191 | n/a | |
---|
192 | n/a | def coroutine(func): |
---|
193 | n/a | """Decorator to mark coroutines. |
---|
194 | n/a | |
---|
195 | n/a | If the coroutine is not yielded from before it is destroyed, |
---|
196 | n/a | an error message is logged. |
---|
197 | n/a | """ |
---|
198 | n/a | if _inspect_iscoroutinefunction(func): |
---|
199 | n/a | # In Python 3.5 that's all we need to do for coroutines |
---|
200 | n/a | # defiend with "async def". |
---|
201 | n/a | # Wrapping in CoroWrapper will happen via |
---|
202 | n/a | # 'sys.set_coroutine_wrapper' function. |
---|
203 | n/a | return func |
---|
204 | n/a | |
---|
205 | n/a | if inspect.isgeneratorfunction(func): |
---|
206 | n/a | coro = func |
---|
207 | n/a | else: |
---|
208 | n/a | @functools.wraps(func) |
---|
209 | n/a | def coro(*args, **kw): |
---|
210 | n/a | res = func(*args, **kw) |
---|
211 | n/a | if (base_futures.isfuture(res) or inspect.isgenerator(res) or |
---|
212 | n/a | isinstance(res, CoroWrapper)): |
---|
213 | n/a | res = yield from res |
---|
214 | n/a | elif _AwaitableABC is not None: |
---|
215 | n/a | # If 'func' returns an Awaitable (new in 3.5) we |
---|
216 | n/a | # want to run it. |
---|
217 | n/a | try: |
---|
218 | n/a | await_meth = res.__await__ |
---|
219 | n/a | except AttributeError: |
---|
220 | n/a | pass |
---|
221 | n/a | else: |
---|
222 | n/a | if isinstance(res, _AwaitableABC): |
---|
223 | n/a | res = yield from await_meth() |
---|
224 | n/a | return res |
---|
225 | n/a | |
---|
226 | n/a | if not _DEBUG: |
---|
227 | n/a | if _types_coroutine is None: |
---|
228 | n/a | wrapper = coro |
---|
229 | n/a | else: |
---|
230 | n/a | wrapper = _types_coroutine(coro) |
---|
231 | n/a | else: |
---|
232 | n/a | @functools.wraps(func) |
---|
233 | n/a | def wrapper(*args, **kwds): |
---|
234 | n/a | w = CoroWrapper(coro(*args, **kwds), func=func) |
---|
235 | n/a | if w._source_traceback: |
---|
236 | n/a | del w._source_traceback[-1] |
---|
237 | n/a | # Python < 3.5 does not implement __qualname__ |
---|
238 | n/a | # on generator objects, so we set it manually. |
---|
239 | n/a | # We use getattr as some callables (such as |
---|
240 | n/a | # functools.partial may lack __qualname__). |
---|
241 | n/a | w.__name__ = getattr(func, '__name__', None) |
---|
242 | n/a | w.__qualname__ = getattr(func, '__qualname__', None) |
---|
243 | n/a | return w |
---|
244 | n/a | |
---|
245 | n/a | wrapper._is_coroutine = _is_coroutine # For iscoroutinefunction(). |
---|
246 | n/a | return wrapper |
---|
247 | n/a | |
---|
248 | n/a | |
---|
249 | n/a | # A marker for iscoroutinefunction. |
---|
250 | n/a | _is_coroutine = object() |
---|
251 | n/a | |
---|
252 | n/a | |
---|
253 | n/a | def iscoroutinefunction(func): |
---|
254 | n/a | """Return True if func is a decorated coroutine function.""" |
---|
255 | n/a | return (getattr(func, '_is_coroutine', None) is _is_coroutine or |
---|
256 | n/a | _inspect_iscoroutinefunction(func)) |
---|
257 | n/a | |
---|
258 | n/a | |
---|
259 | n/a | _COROUTINE_TYPES = (types.GeneratorType, CoroWrapper) |
---|
260 | n/a | if _CoroutineABC is not None: |
---|
261 | n/a | _COROUTINE_TYPES += (_CoroutineABC,) |
---|
262 | n/a | if _types_CoroutineType is not None: |
---|
263 | n/a | # Prioritize native coroutine check to speed-up |
---|
264 | n/a | # asyncio.iscoroutine. |
---|
265 | n/a | _COROUTINE_TYPES = (_types_CoroutineType,) + _COROUTINE_TYPES |
---|
266 | n/a | |
---|
267 | n/a | |
---|
268 | n/a | def iscoroutine(obj): |
---|
269 | n/a | """Return True if obj is a coroutine object.""" |
---|
270 | n/a | return isinstance(obj, _COROUTINE_TYPES) |
---|
271 | n/a | |
---|
272 | n/a | |
---|
273 | n/a | def _format_coroutine(coro): |
---|
274 | n/a | assert iscoroutine(coro) |
---|
275 | n/a | |
---|
276 | n/a | if not hasattr(coro, 'cr_code') and not hasattr(coro, 'gi_code'): |
---|
277 | n/a | # Most likely a built-in type or a Cython coroutine. |
---|
278 | n/a | |
---|
279 | n/a | # Built-in types might not have __qualname__ or __name__. |
---|
280 | n/a | coro_name = getattr( |
---|
281 | n/a | coro, '__qualname__', |
---|
282 | n/a | getattr(coro, '__name__', type(coro).__name__)) |
---|
283 | n/a | coro_name = '{}()'.format(coro_name) |
---|
284 | n/a | |
---|
285 | n/a | running = False |
---|
286 | n/a | try: |
---|
287 | n/a | running = coro.cr_running |
---|
288 | n/a | except AttributeError: |
---|
289 | n/a | try: |
---|
290 | n/a | running = coro.gi_running |
---|
291 | n/a | except AttributeError: |
---|
292 | n/a | pass |
---|
293 | n/a | |
---|
294 | n/a | if running: |
---|
295 | n/a | return '{} running'.format(coro_name) |
---|
296 | n/a | else: |
---|
297 | n/a | return coro_name |
---|
298 | n/a | |
---|
299 | n/a | coro_name = None |
---|
300 | n/a | if isinstance(coro, CoroWrapper): |
---|
301 | n/a | func = coro.func |
---|
302 | n/a | coro_name = coro.__qualname__ |
---|
303 | n/a | if coro_name is not None: |
---|
304 | n/a | coro_name = '{}()'.format(coro_name) |
---|
305 | n/a | else: |
---|
306 | n/a | func = coro |
---|
307 | n/a | |
---|
308 | n/a | if coro_name is None: |
---|
309 | n/a | coro_name = events._format_callback(func, (), {}) |
---|
310 | n/a | |
---|
311 | n/a | try: |
---|
312 | n/a | coro_code = coro.gi_code |
---|
313 | n/a | except AttributeError: |
---|
314 | n/a | coro_code = coro.cr_code |
---|
315 | n/a | |
---|
316 | n/a | try: |
---|
317 | n/a | coro_frame = coro.gi_frame |
---|
318 | n/a | except AttributeError: |
---|
319 | n/a | coro_frame = coro.cr_frame |
---|
320 | n/a | |
---|
321 | n/a | filename = coro_code.co_filename |
---|
322 | n/a | lineno = 0 |
---|
323 | n/a | if (isinstance(coro, CoroWrapper) and |
---|
324 | n/a | not inspect.isgeneratorfunction(coro.func) and |
---|
325 | n/a | coro.func is not None): |
---|
326 | n/a | source = events._get_function_source(coro.func) |
---|
327 | n/a | if source is not None: |
---|
328 | n/a | filename, lineno = source |
---|
329 | n/a | if coro_frame is None: |
---|
330 | n/a | coro_repr = ('%s done, defined at %s:%s' |
---|
331 | n/a | % (coro_name, filename, lineno)) |
---|
332 | n/a | else: |
---|
333 | n/a | coro_repr = ('%s running, defined at %s:%s' |
---|
334 | n/a | % (coro_name, filename, lineno)) |
---|
335 | n/a | elif coro_frame is not None: |
---|
336 | n/a | lineno = coro_frame.f_lineno |
---|
337 | n/a | coro_repr = ('%s running at %s:%s' |
---|
338 | n/a | % (coro_name, filename, lineno)) |
---|
339 | n/a | else: |
---|
340 | n/a | lineno = coro_code.co_firstlineno |
---|
341 | n/a | coro_repr = ('%s done, defined at %s:%s' |
---|
342 | n/a | % (coro_name, filename, lineno)) |
---|
343 | n/a | |
---|
344 | n/a | return coro_repr |
---|