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

/Doc/library/asyncio-dev.rst

https://bitbucket.org/TJG/cpython
ReStructuredText | 396 lines | 281 code | 115 blank | 0 comment | 0 complexity | 2c495ebaad31728d44b7932428f2d4cb MD5 | raw file
Possible License(s): Unlicense, CC-BY-SA-3.0, 0BSD
  1. .. currentmodule:: asyncio
  2. .. _asyncio-dev:
  3. Develop with asyncio
  4. ====================
  5. Asynchronous programming is different than classical "sequential" programming.
  6. This page lists common traps and explains how to avoid them.
  7. .. _asyncio-debug-mode:
  8. Debug mode of asyncio
  9. ---------------------
  10. The implementation of :mod:`asyncio` module has been written for performances.
  11. To development with asyncio, it's required to enable the debug checks to ease
  12. the development of asynchronous code.
  13. Setup an application to enable all debug checks:
  14. * Enable the asyncio debug mode globally by setting the environment variable
  15. :envvar:`PYTHONASYNCIODEBUG` to ``1``
  16. * Set the log level of the :ref:`asyncio logger <asyncio-logger>` to
  17. :py:data:`logging.DEBUG`. For example, call
  18. ``logging.basicConfig(level=logging.DEBUG)`` at startup.
  19. * Configure the :mod:`warnings` module to display :exc:`ResourceWarning`
  20. warnings. For example, use the ``-Wdefault`` command line option of Python to
  21. display them.
  22. Examples debug checks:
  23. * Log :ref:`coroutines defined but never "yielded from"
  24. <asyncio-coroutine-not-scheduled>`
  25. * :meth:`~BaseEventLoop.call_soon` and :meth:`~BaseEventLoop.call_at` methods
  26. raise an exception if they are called from the wrong thread.
  27. * Log the execution time of the selector
  28. * Log callbacks taking more than 100 ms to be executed. The
  29. :attr:`BaseEventLoop.slow_callback_duration` attribute is the minimum
  30. duration in seconds of "slow" callbacks.
  31. * :exc:`ResourceWarning` warnings are emitted when transports and event loops
  32. are :ref:`not closed explicitly <asyncio-close-transports>`.
  33. .. seealso::
  34. The :meth:`BaseEventLoop.set_debug` method and the :ref:`asyncio logger
  35. <asyncio-logger>`.
  36. Cancellation
  37. ------------
  38. Cancellation of tasks is not common in classic programming. In asynchronous
  39. programming, not only it is something common, but you have to prepare your
  40. code to handle it.
  41. Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel`
  42. method. The :func:`wait_for` function cancels the waited task when the timeout
  43. occurs. There are many other cases where a task can be cancelled indirectly.
  44. Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method
  45. of :class:`Future` if the future is cancelled: it would fail with an exception.
  46. For example, write::
  47. if not fut.cancelled():
  48. fut.set_result('done')
  49. Don't schedule directly a call to the :meth:`~Future.set_result` or the
  50. :meth:`~Future.set_exception` method of a future with
  51. :meth:`BaseEventLoop.call_soon`: the future can be cancelled before its method
  52. is called.
  53. If you wait for a future, you should check early if the future was cancelled to
  54. avoid useless operations. Example::
  55. @coroutine
  56. def slow_operation(fut):
  57. if fut.cancelled():
  58. return
  59. # ... slow computation ...
  60. yield from fut
  61. # ...
  62. The :func:`shield` function can also be used to ignore cancellation.
  63. .. _asyncio-multithreading:
  64. Concurrency and multithreading
  65. ------------------------------
  66. An event loop runs in a thread and executes all callbacks and tasks in the same
  67. thread. While a task is running in the event loop, no other task is running in
  68. the same thread. But when the task uses ``yield from``, the task is suspended
  69. and the event loop executes the next task.
  70. To schedule a callback from a different thread, the
  71. :meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example to
  72. schedule a coroutine from a different thread::
  73. loop.call_soon_threadsafe(asyncio.async, coro_func())
  74. Most asyncio objects are not thread safe. You should only worry if you access
  75. objects outside the event loop. For example, to cancel a future, don't call
  76. directly its :meth:`Future.cancel` method, but::
  77. loop.call_soon_threadsafe(fut.cancel)
  78. To handle signals and to execute subprocesses, the event loop must be run in
  79. the main thread.
  80. The :meth:`BaseEventLoop.run_in_executor` method can be used with a thread pool
  81. executor to execute a callback in different thread to not block the thread of
  82. the event loop.
  83. .. seealso::
  84. The :ref:`Synchronization primitives <asyncio-sync>` section describes ways
  85. to synchronize tasks.
  86. The :ref:`Subprocess and threads <asyncio-subprocess-threads>` section lists
  87. asyncio limitations to run subprocesses from different threads.
  88. .. _asyncio-handle-blocking:
  89. Handle blocking functions correctly
  90. -----------------------------------
  91. Blocking functions should not be called directly. For example, if a function
  92. blocks for 1 second, other tasks are delayed by 1 second which can have an
  93. important impact on reactivity.
  94. For networking and subprocesses, the :mod:`asyncio` module provides high-level
  95. APIs like :ref:`protocols <asyncio-protocol>`.
  96. An executor can be used to run a task in a different thread or even in a
  97. different process, to not block the thread of the event loop. See the
  98. :meth:`BaseEventLoop.run_in_executor` method.
  99. .. seealso::
  100. The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the
  101. event loop handles time.
  102. .. _asyncio-logger:
  103. Logging
  104. -------
  105. The :mod:`asyncio` module logs information with the :mod:`logging` module in
  106. the logger ``'asyncio'``.
  107. .. _asyncio-coroutine-not-scheduled:
  108. Detect coroutine objects never scheduled
  109. ----------------------------------------
  110. When a coroutine function is called and its result is not passed to
  111. :func:`async` or to the :meth:`BaseEventLoop.create_task` method, the execution
  112. of the coroutine object will never be scheduled which is probably a bug.
  113. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to :ref:`log a
  114. warning <asyncio-logger>` to detect it.
  115. Example with the bug::
  116. import asyncio
  117. @asyncio.coroutine
  118. def test():
  119. print("never scheduled")
  120. test()
  121. Output in debug mode::
  122. Coroutine test() at test.py:3 was never yielded from
  123. Coroutine object created at (most recent call last):
  124. File "test.py", line 7, in <module>
  125. test()
  126. The fix is to call the :func:`async` function or the
  127. :meth:`BaseEventLoop.create_task` method with the coroutine object.
  128. .. seealso::
  129. :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
  130. Detect exceptions never consumed
  131. --------------------------------
  132. Python usually calls :func:`sys.displayhook` on unhandled exceptions. If
  133. :meth:`Future.set_exception` is called, but the exception is never consumed,
  134. :func:`sys.displayhook` is not called. Instead, :ref:`a log is emitted
  135. <asyncio-logger>` when the future is deleted by the garbage collector, with the
  136. traceback where the exception was raised.
  137. Example of unhandled exception::
  138. import asyncio
  139. @asyncio.coroutine
  140. def bug():
  141. raise Exception("not consumed")
  142. loop = asyncio.get_event_loop()
  143. asyncio.async(bug())
  144. loop.run_forever()
  145. loop.close()
  146. Output::
  147. Task exception was never retrieved
  148. future: <Task finished coro=<coro() done, defined at asyncio/coroutines.py:139> exception=Exception('not consumed',)>
  149. Traceback (most recent call last):
  150. File "asyncio/tasks.py", line 237, in _step
  151. result = next(coro)
  152. File "asyncio/coroutines.py", line 141, in coro
  153. res = func(*args, **kw)
  154. File "test.py", line 5, in bug
  155. raise Exception("not consumed")
  156. Exception: not consumed
  157. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
  158. traceback where the task was created. Output in debug mode::
  159. Task exception was never retrieved
  160. future: <Task finished coro=<bug() done, defined at test.py:3> exception=Exception('not consumed',) created at test.py:8>
  161. source_traceback: Object created at (most recent call last):
  162. File "test.py", line 8, in <module>
  163. asyncio.async(bug())
  164. Traceback (most recent call last):
  165. File "asyncio/tasks.py", line 237, in _step
  166. result = next(coro)
  167. File "asyncio/coroutines.py", line 79, in __next__
  168. return next(self.gen)
  169. File "asyncio/coroutines.py", line 141, in coro
  170. res = func(*args, **kw)
  171. File "test.py", line 5, in bug
  172. raise Exception("not consumed")
  173. Exception: not consumed
  174. There are different options to fix this issue. The first option is to chain the
  175. coroutine in another coroutine and use classic try/except::
  176. @asyncio.coroutine
  177. def handle_exception():
  178. try:
  179. yield from bug()
  180. except Exception:
  181. print("exception consumed")
  182. loop = asyncio.get_event_loop()
  183. asyncio.async(handle_exception())
  184. loop.run_forever()
  185. loop.close()
  186. Another option is to use the :meth:`BaseEventLoop.run_until_complete`
  187. function::
  188. task = asyncio.async(bug())
  189. try:
  190. loop.run_until_complete(task)
  191. except Exception:
  192. print("exception consumed")
  193. .. seealso::
  194. The :meth:`Future.exception` method.
  195. Chain coroutines correctly
  196. --------------------------
  197. When a coroutine function calls other coroutine functions and tasks, they
  198. should be chained explicitly with ``yield from``. Otherwise, the execution is
  199. not guaranteed to be sequential.
  200. Example with different bugs using :func:`asyncio.sleep` to simulate slow
  201. operations::
  202. import asyncio
  203. @asyncio.coroutine
  204. def create():
  205. yield from asyncio.sleep(3.0)
  206. print("(1) create file")
  207. @asyncio.coroutine
  208. def write():
  209. yield from asyncio.sleep(1.0)
  210. print("(2) write into file")
  211. @asyncio.coroutine
  212. def close():
  213. print("(3) close file")
  214. @asyncio.coroutine
  215. def test():
  216. asyncio.async(create())
  217. asyncio.async(write())
  218. asyncio.async(close())
  219. yield from asyncio.sleep(2.0)
  220. loop.stop()
  221. loop = asyncio.get_event_loop()
  222. asyncio.async(test())
  223. loop.run_forever()
  224. print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
  225. loop.close()
  226. Expected output::
  227. (1) create file
  228. (2) write into file
  229. (3) close file
  230. Pending tasks at exit: set()
  231. Actual output::
  232. (3) close file
  233. (2) write into file
  234. Pending tasks at exit: {<Task pending create() at test.py:7 wait_for=<Future pending cb=[Task._wakeup()]>>}
  235. Task was destroyed but it is pending!
  236. task: <Task pending create() done at test.py:5 wait_for=<Future pending cb=[Task._wakeup()]>>
  237. The loop stopped before the ``create()`` finished, ``close()`` has been called
  238. before ``write()``, whereas coroutine functions were called in this order:
  239. ``create()``, ``write()``, ``close()``.
  240. To fix the example, tasks must be marked with ``yield from``::
  241. @asyncio.coroutine
  242. def test():
  243. yield from asyncio.async(create())
  244. yield from asyncio.async(write())
  245. yield from asyncio.async(close())
  246. yield from asyncio.sleep(2.0)
  247. loop.stop()
  248. Or without ``asyncio.async()``::
  249. @asyncio.coroutine
  250. def test():
  251. yield from create()
  252. yield from write()
  253. yield from close()
  254. yield from asyncio.sleep(2.0)
  255. loop.stop()
  256. .. _asyncio-pending-task-destroyed:
  257. Pending task destroyed
  258. ----------------------
  259. If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
  260. <coroutine>` did not complete. It is probably a bug and so a warning is logged.
  261. Example of log::
  262. Task was destroyed but it is pending!
  263. task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()]>>
  264. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
  265. traceback where the task was created. Example of log in debug mode::
  266. Task was destroyed but it is pending!
  267. source_traceback: Object created at (most recent call last):
  268. File "test.py", line 15, in <module>
  269. task = asyncio.async(coro, loop=loop)
  270. task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()] created at test.py:7> created at test.py:15>
  271. .. seealso::
  272. :ref:`Detect coroutine objects never scheduled <asyncio-coroutine-not-scheduled>`.
  273. .. _asyncio-close-transports:
  274. Close transports and event loops
  275. --------------------------------
  276. When a transport is no more needed, call its ``close()`` method to release
  277. resources. Event loops must also be closed explicitly.
  278. If a transport or an event loop is not closed explicitly, a
  279. :exc:`ResourceWarning` warning will be emitted in its destructor. By default,
  280. :exc:`ResourceWarning` warnings are ignored. The :ref:`Debug mode of asyncio
  281. <asyncio-debug-mode>` section explains how to display them.