PageRenderTime 78ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/asyncio/tasks.py

https://bitbucket.org/ncoghlan/cpython_sandbox
Python | 791 lines | 689 code | 29 blank | 73 comment | 38 complexity | cb17b17ab7570f9fdf7b92d74c135d78 MD5 | raw file
Possible License(s): BSD-3-Clause, Unlicense, CC-BY-SA-3.0, 0BSD
  1. """Support for tasks, coroutines and the scheduler."""
  2. __all__ = ['Task',
  3. 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
  4. 'wait', 'wait_for', 'as_completed', 'sleep', 'async',
  5. 'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
  6. 'timeout',
  7. ]
  8. import concurrent.futures
  9. import functools
  10. import inspect
  11. import linecache
  12. import traceback
  13. import warnings
  14. import weakref
  15. from . import compat
  16. from . import coroutines
  17. from . import events
  18. from . import futures
  19. from .coroutines import coroutine
  20. class Task(futures.Future):
  21. """A coroutine wrapped in a Future."""
  22. # An important invariant maintained while a Task not done:
  23. #
  24. # - Either _fut_waiter is None, and _step() is scheduled;
  25. # - or _fut_waiter is some Future, and _step() is *not* scheduled.
  26. #
  27. # The only transition from the latter to the former is through
  28. # _wakeup(). When _fut_waiter is not None, one of its callbacks
  29. # must be _wakeup().
  30. # Weak set containing all tasks alive.
  31. _all_tasks = weakref.WeakSet()
  32. # Dictionary containing tasks that are currently active in
  33. # all running event loops. {EventLoop: Task}
  34. _current_tasks = {}
  35. # If False, don't log a message if the task is destroyed whereas its
  36. # status is still pending
  37. _log_destroy_pending = True
  38. @classmethod
  39. def current_task(cls, loop=None):
  40. """Return the currently running task in an event loop or None.
  41. By default the current task for the current event loop is returned.
  42. None is returned when called not in the context of a Task.
  43. """
  44. if loop is None:
  45. loop = events.get_event_loop()
  46. return cls._current_tasks.get(loop)
  47. @classmethod
  48. def all_tasks(cls, loop=None):
  49. """Return a set of all tasks for an event loop.
  50. By default all tasks for the current event loop are returned.
  51. """
  52. if loop is None:
  53. loop = events.get_event_loop()
  54. return {t for t in cls._all_tasks if t._loop is loop}
  55. def __init__(self, coro, *, loop=None):
  56. assert coroutines.iscoroutine(coro), repr(coro)
  57. super().__init__(loop=loop)
  58. if self._source_traceback:
  59. del self._source_traceback[-1]
  60. self._coro = coro
  61. self._fut_waiter = None
  62. self._must_cancel = False
  63. self._loop.call_soon(self._step)
  64. self.__class__._all_tasks.add(self)
  65. # On Python 3.3 or older, objects with a destructor that are part of a
  66. # reference cycle are never destroyed. That's not the case any more on
  67. # Python 3.4 thanks to the PEP 442.
  68. if compat.PY34:
  69. def __del__(self):
  70. if self._state == futures._PENDING and self._log_destroy_pending:
  71. context = {
  72. 'task': self,
  73. 'message': 'Task was destroyed but it is pending!',
  74. }
  75. if self._source_traceback:
  76. context['source_traceback'] = self._source_traceback
  77. self._loop.call_exception_handler(context)
  78. futures.Future.__del__(self)
  79. def _repr_info(self):
  80. info = super()._repr_info()
  81. if self._must_cancel:
  82. # replace status
  83. info[0] = 'cancelling'
  84. coro = coroutines._format_coroutine(self._coro)
  85. info.insert(1, 'coro=<%s>' % coro)
  86. if self._fut_waiter is not None:
  87. info.insert(2, 'wait_for=%r' % self._fut_waiter)
  88. return info
  89. def get_stack(self, *, limit=None):
  90. """Return the list of stack frames for this task's coroutine.
  91. If the coroutine is not done, this returns the stack where it is
  92. suspended. If the coroutine has completed successfully or was
  93. cancelled, this returns an empty list. If the coroutine was
  94. terminated by an exception, this returns the list of traceback
  95. frames.
  96. The frames are always ordered from oldest to newest.
  97. The optional limit gives the maximum number of frames to
  98. return; by default all available frames are returned. Its
  99. meaning differs depending on whether a stack or a traceback is
  100. returned: the newest frames of a stack are returned, but the
  101. oldest frames of a traceback are returned. (This matches the
  102. behavior of the traceback module.)
  103. For reasons beyond our control, only one stack frame is
  104. returned for a suspended coroutine.
  105. """
  106. frames = []
  107. try:
  108. # 'async def' coroutines
  109. f = self._coro.cr_frame
  110. except AttributeError:
  111. f = self._coro.gi_frame
  112. if f is not None:
  113. while f is not None:
  114. if limit is not None:
  115. if limit <= 0:
  116. break
  117. limit -= 1
  118. frames.append(f)
  119. f = f.f_back
  120. frames.reverse()
  121. elif self._exception is not None:
  122. tb = self._exception.__traceback__
  123. while tb is not None:
  124. if limit is not None:
  125. if limit <= 0:
  126. break
  127. limit -= 1
  128. frames.append(tb.tb_frame)
  129. tb = tb.tb_next
  130. return frames
  131. def print_stack(self, *, limit=None, file=None):
  132. """Print the stack or traceback for this task's coroutine.
  133. This produces output similar to that of the traceback module,
  134. for the frames retrieved by get_stack(). The limit argument
  135. is passed to get_stack(). The file argument is an I/O stream
  136. to which the output is written; by default output is written
  137. to sys.stderr.
  138. """
  139. extracted_list = []
  140. checked = set()
  141. for f in self.get_stack(limit=limit):
  142. lineno = f.f_lineno
  143. co = f.f_code
  144. filename = co.co_filename
  145. name = co.co_name
  146. if filename not in checked:
  147. checked.add(filename)
  148. linecache.checkcache(filename)
  149. line = linecache.getline(filename, lineno, f.f_globals)
  150. extracted_list.append((filename, lineno, name, line))
  151. exc = self._exception
  152. if not extracted_list:
  153. print('No stack for %r' % self, file=file)
  154. elif exc is not None:
  155. print('Traceback for %r (most recent call last):' % self,
  156. file=file)
  157. else:
  158. print('Stack for %r (most recent call last):' % self,
  159. file=file)
  160. traceback.print_list(extracted_list, file=file)
  161. if exc is not None:
  162. for line in traceback.format_exception_only(exc.__class__, exc):
  163. print(line, file=file, end='')
  164. def cancel(self):
  165. """Request that this task cancel itself.
  166. This arranges for a CancelledError to be thrown into the
  167. wrapped coroutine on the next cycle through the event loop.
  168. The coroutine then has a chance to clean up or even deny
  169. the request using try/except/finally.
  170. Unlike Future.cancel, this does not guarantee that the
  171. task will be cancelled: the exception might be caught and
  172. acted upon, delaying cancellation of the task or preventing
  173. cancellation completely. The task may also return a value or
  174. raise a different exception.
  175. Immediately after this method is called, Task.cancelled() will
  176. not return True (unless the task was already cancelled). A
  177. task will be marked as cancelled when the wrapped coroutine
  178. terminates with a CancelledError exception (even if cancel()
  179. was not called).
  180. """
  181. if self.done():
  182. return False
  183. if self._fut_waiter is not None:
  184. if self._fut_waiter.cancel():
  185. # Leave self._fut_waiter; it may be a Task that
  186. # catches and ignores the cancellation so we may have
  187. # to cancel it again later.
  188. return True
  189. # It must be the case that self._step is already scheduled.
  190. self._must_cancel = True
  191. return True
  192. def _step(self, exc=None):
  193. assert not self.done(), \
  194. '_step(): already done: {!r}, {!r}'.format(self, exc)
  195. if self._must_cancel:
  196. if not isinstance(exc, futures.CancelledError):
  197. exc = futures.CancelledError()
  198. self._must_cancel = False
  199. coro = self._coro
  200. self._fut_waiter = None
  201. self.__class__._current_tasks[self._loop] = self
  202. # Call either coro.throw(exc) or coro.send(None).
  203. try:
  204. if exc is None:
  205. # We use the `send` method directly, because coroutines
  206. # don't have `__iter__` and `__next__` methods.
  207. result = coro.send(None)
  208. else:
  209. result = coro.throw(exc)
  210. except StopIteration as exc:
  211. self.set_result(exc.value)
  212. except futures.CancelledError as exc:
  213. super().cancel() # I.e., Future.cancel(self).
  214. except Exception as exc:
  215. self.set_exception(exc)
  216. except BaseException as exc:
  217. self.set_exception(exc)
  218. raise
  219. else:
  220. if isinstance(result, futures.Future):
  221. # Yielded Future must come from Future.__iter__().
  222. if result._loop is not self._loop:
  223. self._loop.call_soon(
  224. self._step,
  225. RuntimeError(
  226. 'Task {!r} got Future {!r} attached to a '
  227. 'different loop'.format(self, result)))
  228. elif result._blocking:
  229. result._blocking = False
  230. result.add_done_callback(self._wakeup)
  231. self._fut_waiter = result
  232. if self._must_cancel:
  233. if self._fut_waiter.cancel():
  234. self._must_cancel = False
  235. else:
  236. self._loop.call_soon(
  237. self._step,
  238. RuntimeError(
  239. 'yield was used instead of yield from '
  240. 'in task {!r} with {!r}'.format(self, result)))
  241. elif result is None:
  242. # Bare yield relinquishes control for one event loop iteration.
  243. self._loop.call_soon(self._step)
  244. elif inspect.isgenerator(result):
  245. # Yielding a generator is just wrong.
  246. self._loop.call_soon(
  247. self._step,
  248. RuntimeError(
  249. 'yield was used instead of yield from for '
  250. 'generator in task {!r} with {}'.format(
  251. self, result)))
  252. else:
  253. # Yielding something else is an error.
  254. self._loop.call_soon(
  255. self._step,
  256. RuntimeError(
  257. 'Task got bad yield: {!r}'.format(result)))
  258. finally:
  259. self.__class__._current_tasks.pop(self._loop)
  260. self = None # Needed to break cycles when an exception occurs.
  261. def _wakeup(self, future):
  262. try:
  263. future.result()
  264. except Exception as exc:
  265. # This may also be a cancellation.
  266. self._step(exc)
  267. else:
  268. # Don't pass the value of `future.result()` explicitly,
  269. # as `Future.__iter__` and `Future.__await__` don't need it.
  270. # If we call `_step(value, None)` instead of `_step()`,
  271. # Python eval loop would use `.send(value)` method call,
  272. # instead of `__next__()`, which is slower for futures
  273. # that return non-generator iterators from their `__iter__`.
  274. self._step()
  275. self = None # Needed to break cycles when an exception occurs.
  276. # wait() and as_completed() similar to those in PEP 3148.
  277. FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
  278. FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
  279. ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
  280. @coroutine
  281. def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
  282. """Wait for the Futures and coroutines given by fs to complete.
  283. The sequence futures must not be empty.
  284. Coroutines will be wrapped in Tasks.
  285. Returns two sets of Future: (done, pending).
  286. Usage:
  287. done, pending = yield from asyncio.wait(fs)
  288. Note: This does not raise TimeoutError! Futures that aren't done
  289. when the timeout occurs are returned in the second set.
  290. """
  291. if isinstance(fs, futures.Future) or coroutines.iscoroutine(fs):
  292. raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
  293. if not fs:
  294. raise ValueError('Set of coroutines/Futures is empty.')
  295. if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
  296. raise ValueError('Invalid return_when value: {}'.format(return_when))
  297. if loop is None:
  298. loop = events.get_event_loop()
  299. fs = {ensure_future(f, loop=loop) for f in set(fs)}
  300. return (yield from _wait(fs, timeout, return_when, loop))
  301. def _release_waiter(waiter, *args):
  302. if not waiter.done():
  303. waiter.set_result(None)
  304. @coroutine
  305. def wait_for(fut, timeout, *, loop=None):
  306. """Wait for the single Future or coroutine to complete, with timeout.
  307. Coroutine will be wrapped in Task.
  308. Returns result of the Future or coroutine. When a timeout occurs,
  309. it cancels the task and raises TimeoutError. To avoid the task
  310. cancellation, wrap it in shield().
  311. If the wait is cancelled, the task is also cancelled.
  312. This function is a coroutine.
  313. """
  314. if loop is None:
  315. loop = events.get_event_loop()
  316. if timeout is None:
  317. return (yield from fut)
  318. waiter = loop.create_future()
  319. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  320. cb = functools.partial(_release_waiter, waiter)
  321. fut = ensure_future(fut, loop=loop)
  322. fut.add_done_callback(cb)
  323. try:
  324. # wait until the future completes or the timeout
  325. try:
  326. yield from waiter
  327. except futures.CancelledError:
  328. fut.remove_done_callback(cb)
  329. fut.cancel()
  330. raise
  331. if fut.done():
  332. return fut.result()
  333. else:
  334. fut.remove_done_callback(cb)
  335. fut.cancel()
  336. raise futures.TimeoutError()
  337. finally:
  338. timeout_handle.cancel()
  339. @coroutine
  340. def _wait(fs, timeout, return_when, loop):
  341. """Internal helper for wait() and wait_for().
  342. The fs argument must be a collection of Futures.
  343. """
  344. assert fs, 'Set of Futures is empty.'
  345. waiter = loop.create_future()
  346. timeout_handle = None
  347. if timeout is not None:
  348. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  349. counter = len(fs)
  350. def _on_completion(f):
  351. nonlocal counter
  352. counter -= 1
  353. if (counter <= 0 or
  354. return_when == FIRST_COMPLETED or
  355. return_when == FIRST_EXCEPTION and (not f.cancelled() and
  356. f.exception() is not None)):
  357. if timeout_handle is not None:
  358. timeout_handle.cancel()
  359. if not waiter.done():
  360. waiter.set_result(None)
  361. for f in fs:
  362. f.add_done_callback(_on_completion)
  363. try:
  364. yield from waiter
  365. finally:
  366. if timeout_handle is not None:
  367. timeout_handle.cancel()
  368. done, pending = set(), set()
  369. for f in fs:
  370. f.remove_done_callback(_on_completion)
  371. if f.done():
  372. done.add(f)
  373. else:
  374. pending.add(f)
  375. return done, pending
  376. # This is *not* a @coroutine! It is just an iterator (yielding Futures).
  377. def as_completed(fs, *, loop=None, timeout=None):
  378. """Return an iterator whose values are coroutines.
  379. When waiting for the yielded coroutines you'll get the results (or
  380. exceptions!) of the original Futures (or coroutines), in the order
  381. in which and as soon as they complete.
  382. This differs from PEP 3148; the proper way to use this is:
  383. for f in as_completed(fs):
  384. result = yield from f # The 'yield from' may raise.
  385. # Use result.
  386. If a timeout is specified, the 'yield from' will raise
  387. TimeoutError when the timeout occurs before all Futures are done.
  388. Note: The futures 'f' are not necessarily members of fs.
  389. """
  390. if isinstance(fs, futures.Future) or coroutines.iscoroutine(fs):
  391. raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
  392. loop = loop if loop is not None else events.get_event_loop()
  393. todo = {ensure_future(f, loop=loop) for f in set(fs)}
  394. from .queues import Queue # Import here to avoid circular import problem.
  395. done = Queue(loop=loop)
  396. timeout_handle = None
  397. def _on_timeout():
  398. for f in todo:
  399. f.remove_done_callback(_on_completion)
  400. done.put_nowait(None) # Queue a dummy value for _wait_for_one().
  401. todo.clear() # Can't do todo.remove(f) in the loop.
  402. def _on_completion(f):
  403. if not todo:
  404. return # _on_timeout() was here first.
  405. todo.remove(f)
  406. done.put_nowait(f)
  407. if not todo and timeout_handle is not None:
  408. timeout_handle.cancel()
  409. @coroutine
  410. def _wait_for_one():
  411. f = yield from done.get()
  412. if f is None:
  413. # Dummy value from _on_timeout().
  414. raise futures.TimeoutError
  415. return f.result() # May raise f.exception().
  416. for f in todo:
  417. f.add_done_callback(_on_completion)
  418. if todo and timeout is not None:
  419. timeout_handle = loop.call_later(timeout, _on_timeout)
  420. for _ in range(len(todo)):
  421. yield _wait_for_one()
  422. @coroutine
  423. def sleep(delay, result=None, *, loop=None):
  424. """Coroutine that completes after a given time (in seconds)."""
  425. if delay == 0:
  426. yield
  427. return result
  428. if loop is None:
  429. loop = events.get_event_loop()
  430. future = loop.create_future()
  431. h = future._loop.call_later(delay,
  432. futures._set_result_unless_cancelled,
  433. future, result)
  434. try:
  435. return (yield from future)
  436. finally:
  437. h.cancel()
  438. def async(coro_or_future, *, loop=None):
  439. """Wrap a coroutine in a future.
  440. If the argument is a Future, it is returned directly.
  441. This function is deprecated in 3.5. Use asyncio.ensure_future() instead.
  442. """
  443. warnings.warn("asyncio.async() function is deprecated, use ensure_future()",
  444. DeprecationWarning)
  445. return ensure_future(coro_or_future, loop=loop)
  446. def ensure_future(coro_or_future, *, loop=None):
  447. """Wrap a coroutine or an awaitable in a future.
  448. If the argument is a Future, it is returned directly.
  449. """
  450. if isinstance(coro_or_future, futures.Future):
  451. if loop is not None and loop is not coro_or_future._loop:
  452. raise ValueError('loop argument must agree with Future')
  453. return coro_or_future
  454. elif coroutines.iscoroutine(coro_or_future):
  455. if loop is None:
  456. loop = events.get_event_loop()
  457. task = loop.create_task(coro_or_future)
  458. if task._source_traceback:
  459. del task._source_traceback[-1]
  460. return task
  461. elif compat.PY35 and inspect.isawaitable(coro_or_future):
  462. return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
  463. else:
  464. raise TypeError('A Future, a coroutine or an awaitable is required')
  465. @coroutine
  466. def _wrap_awaitable(awaitable):
  467. """Helper for asyncio.ensure_future().
  468. Wraps awaitable (an object with __await__) into a coroutine
  469. that will later be wrapped in a Task by ensure_future().
  470. """
  471. return (yield from awaitable.__await__())
  472. class _GatheringFuture(futures.Future):
  473. """Helper for gather().
  474. This overrides cancel() to cancel all the children and act more
  475. like Task.cancel(), which doesn't immediately mark itself as
  476. cancelled.
  477. """
  478. def __init__(self, children, *, loop=None):
  479. super().__init__(loop=loop)
  480. self._children = children
  481. def cancel(self):
  482. if self.done():
  483. return False
  484. for child in self._children:
  485. child.cancel()
  486. return True
  487. def gather(*coros_or_futures, loop=None, return_exceptions=False):
  488. """Return a future aggregating results from the given coroutines
  489. or futures.
  490. All futures must share the same event loop. If all the tasks are
  491. done successfully, the returned future's result is the list of
  492. results (in the order of the original sequence, not necessarily
  493. the order of results arrival). If *return_exceptions* is True,
  494. exceptions in the tasks are treated the same as successful
  495. results, and gathered in the result list; otherwise, the first
  496. raised exception will be immediately propagated to the returned
  497. future.
  498. Cancellation: if the outer Future is cancelled, all children (that
  499. have not completed yet) are also cancelled. If any child is
  500. cancelled, this is treated as if it raised CancelledError --
  501. the outer Future is *not* cancelled in this case. (This is to
  502. prevent the cancellation of one child to cause other children to
  503. be cancelled.)
  504. """
  505. if not coros_or_futures:
  506. if loop is None:
  507. loop = events.get_event_loop()
  508. outer = loop.create_future()
  509. outer.set_result([])
  510. return outer
  511. arg_to_fut = {}
  512. for arg in set(coros_or_futures):
  513. if not isinstance(arg, futures.Future):
  514. fut = ensure_future(arg, loop=loop)
  515. if loop is None:
  516. loop = fut._loop
  517. # The caller cannot control this future, the "destroy pending task"
  518. # warning should not be emitted.
  519. fut._log_destroy_pending = False
  520. else:
  521. fut = arg
  522. if loop is None:
  523. loop = fut._loop
  524. elif fut._loop is not loop:
  525. raise ValueError("futures are tied to different event loops")
  526. arg_to_fut[arg] = fut
  527. children = [arg_to_fut[arg] for arg in coros_or_futures]
  528. nchildren = len(children)
  529. outer = _GatheringFuture(children, loop=loop)
  530. nfinished = 0
  531. results = [None] * nchildren
  532. def _done_callback(i, fut):
  533. nonlocal nfinished
  534. if outer.done():
  535. if not fut.cancelled():
  536. # Mark exception retrieved.
  537. fut.exception()
  538. return
  539. if fut.cancelled():
  540. res = futures.CancelledError()
  541. if not return_exceptions:
  542. outer.set_exception(res)
  543. return
  544. elif fut._exception is not None:
  545. res = fut.exception() # Mark exception retrieved.
  546. if not return_exceptions:
  547. outer.set_exception(res)
  548. return
  549. else:
  550. res = fut._result
  551. results[i] = res
  552. nfinished += 1
  553. if nfinished == nchildren:
  554. outer.set_result(results)
  555. for i, fut in enumerate(children):
  556. fut.add_done_callback(functools.partial(_done_callback, i))
  557. return outer
  558. def shield(arg, *, loop=None):
  559. """Wait for a future, shielding it from cancellation.
  560. The statement
  561. res = yield from shield(something())
  562. is exactly equivalent to the statement
  563. res = yield from something()
  564. *except* that if the coroutine containing it is cancelled, the
  565. task running in something() is not cancelled. From the POV of
  566. something(), the cancellation did not happen. But its caller is
  567. still cancelled, so the yield-from expression still raises
  568. CancelledError. Note: If something() is cancelled by other means
  569. this will still cancel shield().
  570. If you want to completely ignore cancellation (not recommended)
  571. you can combine shield() with a try/except clause, as follows:
  572. try:
  573. res = yield from shield(something())
  574. except CancelledError:
  575. res = None
  576. """
  577. inner = ensure_future(arg, loop=loop)
  578. if inner.done():
  579. # Shortcut.
  580. return inner
  581. loop = inner._loop
  582. outer = loop.create_future()
  583. def _done_callback(inner):
  584. if outer.cancelled():
  585. if not inner.cancelled():
  586. # Mark inner's result as retrieved.
  587. inner.exception()
  588. return
  589. if inner.cancelled():
  590. outer.cancel()
  591. else:
  592. exc = inner.exception()
  593. if exc is not None:
  594. outer.set_exception(exc)
  595. else:
  596. outer.set_result(inner.result())
  597. inner.add_done_callback(_done_callback)
  598. return outer
  599. def run_coroutine_threadsafe(coro, loop):
  600. """Submit a coroutine object to a given event loop.
  601. Return a concurrent.futures.Future to access the result.
  602. """
  603. if not coroutines.iscoroutine(coro):
  604. raise TypeError('A coroutine object is required')
  605. future = concurrent.futures.Future()
  606. def callback():
  607. try:
  608. futures._chain_future(ensure_future(coro, loop=loop), future)
  609. except Exception as exc:
  610. if future.set_running_or_notify_cancel():
  611. future.set_exception(exc)
  612. raise
  613. loop.call_soon_threadsafe(callback)
  614. return future
  615. def timeout(timeout, *, loop=None):
  616. """A factory which produce a context manager with timeout.
  617. Useful in cases when you want to apply timeout logic around block
  618. of code or in cases when asyncio.wait_for is not suitable.
  619. For example:
  620. >>> with asyncio.timeout(0.001):
  621. ... yield from coro()
  622. timeout: timeout value in seconds or None to disable timeout logic
  623. loop: asyncio compatible event loop
  624. """
  625. if loop is None:
  626. loop = events.get_event_loop()
  627. return _Timeout(timeout, loop=loop)
  628. class _Timeout:
  629. def __init__(self, timeout, *, loop):
  630. self._timeout = timeout
  631. self._loop = loop
  632. self._task = None
  633. self._cancelled = False
  634. self._cancel_handler = None
  635. def __enter__(self):
  636. self._task = Task.current_task(loop=self._loop)
  637. if self._task is None:
  638. raise RuntimeError('Timeout context manager should be used '
  639. 'inside a task')
  640. if self._timeout is not None:
  641. self._cancel_handler = self._loop.call_later(
  642. self._timeout, self._cancel_task)
  643. return self
  644. def __exit__(self, exc_type, exc_val, exc_tb):
  645. if exc_type is futures.CancelledError and self._cancelled:
  646. self._cancel_handler = None
  647. self._task = None
  648. raise futures.TimeoutError
  649. if self._timeout is not None:
  650. self._cancel_handler.cancel()
  651. self._cancel_handler = None
  652. self._task = None
  653. def _cancel_task(self):
  654. self._cancelled = self._task.cancel()