blob: bf77a8fb794573e494875fb117b4d1598f264dbb [file] [log] [blame]
Victor Stinnerdb39a0d2014-01-16 18:58:01 +01001.. currentmodule:: asyncio
2
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01003.. _asyncio-dev:
4
Victor Stinnerdb39a0d2014-01-16 18:58:01 +01005Develop with asyncio
6====================
7
8Asynchronous programming is different than classical "sequential" programming.
Eli Bendersky679688e2014-01-20 08:13:31 -08009This page lists common traps and explains how to avoid them.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010010
11
Victor Stinner62511fd2014-06-23 00:36:11 +020012.. _asyncio-debug-mode:
13
14Debug mode of asyncio
15---------------------
16
Victor Stinner6a1b0042015-02-04 16:14:33 +010017The implementation of :mod:`asyncio` module has been written for performances.
18To development with asyncio, it's required to enable the debug checks to ease
19the development of asynchronous code.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +020020
Victor Stinner6a1b0042015-02-04 16:14:33 +010021Setup an application to enable all debug checks:
Victor Stinnerd71dcbb2014-08-25 17:04:12 +020022
Victor Stinner6a1b0042015-02-04 16:14:33 +010023* Enable the asyncio debug mode globally by setting the environment variable
24 :envvar:`PYTHONASYNCIODEBUG` to ``1``
25* Set the log level of the :ref:`asyncio logger <asyncio-logger>` to
26 :py:data:`logging.DEBUG`. For example, call
27 ``logging.basicConfig(level=logging.DEBUG)`` at startup.
28* Configure the :mod:`warnings` module to display :exc:`ResourceWarning`
29 warnings. For example, use the ``-Wdefault`` command line option of Python to
30 display them.
31
32Examples debug checks:
Victor Stinner62511fd2014-06-23 00:36:11 +020033
34* Log :ref:`coroutines defined but never "yielded from"
35 <asyncio-coroutine-not-scheduled>`
36* :meth:`~BaseEventLoop.call_soon` and :meth:`~BaseEventLoop.call_at` methods
37 raise an exception if they are called from the wrong thread.
38* Log the execution time of the selector
39* Log callbacks taking more than 100 ms to be executed. The
40 :attr:`BaseEventLoop.slow_callback_duration` attribute is the minimum
41 duration in seconds of "slow" callbacks.
Victor Stinner6a1b0042015-02-04 16:14:33 +010042* :exc:`ResourceWarning` warnings are emitted when transports and event loops
43 are :ref:`not closed explicitly <asyncio-close-transports>`.
Victor Stinner62511fd2014-06-23 00:36:11 +020044
45.. seealso::
46
47 The :meth:`BaseEventLoop.set_debug` method and the :ref:`asyncio logger
48 <asyncio-logger>`.
49
50
Victor Stinner1077dee2015-01-30 00:55:58 +010051Cancellation
52------------
53
54Cancellation of tasks is not common in classic programming. In asynchronous
55programming, not only it is something common, but you have to prepare your
56code to handle it.
57
58Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel`
59method. The :func:`wait_for` function cancels the waited task when the timeout
60occurs. There are many other cases where a task can be cancelled indirectly.
61
62Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method
63of :class:`Future` if the future is cancelled: it would fail with an exception.
64For example, write::
65
66 if not fut.cancelled():
67 fut.set_result('done')
68
69Don't schedule directly a call to the :meth:`~Future.set_result` or the
70:meth:`~Future.set_exception` method of a future with
71:meth:`BaseEventLoop.call_soon`: the future can be cancelled before its method
72is called.
73
74If you wait for a future, you should check early if the future was cancelled to
75avoid useless operations. Example::
76
77 @coroutine
78 def slow_operation(fut):
79 if fut.cancelled():
80 return
81 # ... slow computation ...
82 yield from fut
83 # ...
84
85The :func:`shield` function can also be used to ignore cancellation.
86
87
Victor Stinner606ab032014-02-01 03:18:58 +010088.. _asyncio-multithreading:
89
90Concurrency and multithreading
91------------------------------
92
93An event loop runs in a thread and executes all callbacks and tasks in the same
Victor Stinner86516d92014-02-18 09:22:00 +010094thread. While a task is running in the event loop, no other task is running in
Victor Stinner5cb84ed2014-02-04 18:18:27 +010095the same thread. But when the task uses ``yield from``, the task is suspended
96and the event loop executes the next task.
Victor Stinner606ab032014-02-01 03:18:58 +010097
Victor Stinner5cb84ed2014-02-04 18:18:27 +010098To schedule a callback from a different thread, the
99:meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example to
Guido van Rossum3c9bb692014-02-04 13:49:34 -0800100schedule a coroutine from a different thread::
Victor Stinner5cb84ed2014-02-04 18:18:27 +0100101
102 loop.call_soon_threadsafe(asyncio.async, coro_func())
Victor Stinner606ab032014-02-01 03:18:58 +0100103
Victor Stinner790202d2014-02-07 19:03:05 +0100104Most asyncio objects are not thread safe. You should only worry if you access
105objects outside the event loop. For example, to cancel a future, don't call
106directly its :meth:`Future.cancel` method, but::
107
108 loop.call_soon_threadsafe(fut.cancel)
109
Victor Stinner606ab032014-02-01 03:18:58 +0100110To handle signals and to execute subprocesses, the event loop must be run in
111the main thread.
112
113The :meth:`BaseEventLoop.run_in_executor` method can be used with a thread pool
114executor to execute a callback in different thread to not block the thread of
115the event loop.
116
117.. seealso::
118
Zachary Ware5819cfa2015-01-06 00:40:43 -0600119 The :ref:`Synchronization primitives <asyncio-sync>` section describes ways
120 to synchronize tasks.
Victor Stinner606ab032014-02-01 03:18:58 +0100121
Victor Stinner399c59d2015-01-09 01:32:02 +0100122 The :ref:`Subprocess and threads <asyncio-subprocess-threads>` section lists
123 asyncio limitations to run subprocesses from different threads.
124
125
126
Victor Stinner606ab032014-02-01 03:18:58 +0100127
Victor Stinner45b27ed2014-02-01 02:36:43 +0100128.. _asyncio-handle-blocking:
129
Eli Benderskyb73c8332014-02-09 06:07:47 -0800130Handle blocking functions correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100131-----------------------------------
132
133Blocking functions should not be called directly. For example, if a function
134blocks for 1 second, other tasks are delayed by 1 second which can have an
135important impact on reactivity.
136
137For networking and subprocesses, the :mod:`asyncio` module provides high-level
Victor Stinner9592edb2014-02-02 15:03:02 +0100138APIs like :ref:`protocols <asyncio-protocol>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100139
140An executor can be used to run a task in a different thread or even in a
141different process, to not block the thread of the event loop. See the
Victor Stinner606ab032014-02-01 03:18:58 +0100142:meth:`BaseEventLoop.run_in_executor` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100143
Victor Stinner45b27ed2014-02-01 02:36:43 +0100144.. seealso::
145
146 The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the
147 event loop handles time.
148
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100149
150.. _asyncio-logger:
151
Victor Stinner45b27ed2014-02-01 02:36:43 +0100152Logging
153-------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100154
Victor Stinner45b27ed2014-02-01 02:36:43 +0100155The :mod:`asyncio` module logs information with the :mod:`logging` module in
156the logger ``'asyncio'``.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100157
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100158
159.. _asyncio-coroutine-not-scheduled:
160
161Detect coroutine objects never scheduled
162----------------------------------------
163
Victor Stinner530ef2f2014-07-08 12:39:10 +0200164When a coroutine function is called and its result is not passed to
Zachary Ware5819cfa2015-01-06 00:40:43 -0600165:func:`async` or to the :meth:`BaseEventLoop.create_task` method, the execution
166of the coroutine object will never be scheduled which is probably a bug.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200167:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to :ref:`log a
168warning <asyncio-logger>` to detect it.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100169
170Example with the bug::
171
172 import asyncio
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100173
174 @asyncio.coroutine
175 def test():
176 print("never scheduled")
177
178 test()
179
180Output in debug mode::
181
Victor Stinner530ef2f2014-07-08 12:39:10 +0200182 Coroutine test() at test.py:3 was never yielded from
183 Coroutine object created at (most recent call last):
184 File "test.py", line 7, in <module>
185 test()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100186
Victor Stinner530ef2f2014-07-08 12:39:10 +0200187The fix is to call the :func:`async` function or the
188:meth:`BaseEventLoop.create_task` method with the coroutine object.
189
190.. seealso::
191
192 :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100193
194
Victor Stinner530ef2f2014-07-08 12:39:10 +0200195Detect exceptions never consumed
196--------------------------------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100197
198Python usually calls :func:`sys.displayhook` on unhandled exceptions. If
Victor Stinner530ef2f2014-07-08 12:39:10 +0200199:meth:`Future.set_exception` is called, but the exception is never consumed,
Zachary Ware5819cfa2015-01-06 00:40:43 -0600200:func:`sys.displayhook` is not called. Instead, :ref:`a log is emitted
Victor Stinner530ef2f2014-07-08 12:39:10 +0200201<asyncio-logger>` when the future is deleted by the garbage collector, with the
202traceback where the exception was raised.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100203
204Example of unhandled exception::
205
206 import asyncio
207
208 @asyncio.coroutine
209 def bug():
210 raise Exception("not consumed")
211
212 loop = asyncio.get_event_loop()
213 asyncio.async(bug())
214 loop.run_forever()
215
216Output::
217
Victor Stinner530ef2f2014-07-08 12:39:10 +0200218 Task exception was never retrieved
Victor Stinnerab1c8532014-10-12 21:37:16 +0200219 future: <Task finished coro=<coro() done, defined at asyncio/coroutines.py:139> exception=Exception('not consumed',)>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100220 Traceback (most recent call last):
Victor Stinnerab1c8532014-10-12 21:37:16 +0200221 File "asyncio/tasks.py", line 237, in _step
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100222 result = next(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200223 File "asyncio/coroutines.py", line 141, in coro
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100224 res = func(*args, **kw)
Victor Stinnerab1c8532014-10-12 21:37:16 +0200225 File "test.py", line 5, in bug
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100226 raise Exception("not consumed")
227 Exception: not consumed
228
Victor Stinner530ef2f2014-07-08 12:39:10 +0200229:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Victor Stinnerab1c8532014-10-12 21:37:16 +0200230traceback where the task was created. Output in debug mode::
231
232 Task exception was never retrieved
233 future: <Task finished coro=<bug() done, defined at test.py:3> exception=Exception('not consumed',) created at test.py:8>
234 source_traceback: Object created at (most recent call last):
235 File "test.py", line 8, in <module>
236 asyncio.async(bug())
237 Traceback (most recent call last):
238 File "asyncio/tasks.py", line 237, in _step
239 result = next(coro)
240 File "asyncio/coroutines.py", line 79, in __next__
241 return next(self.gen)
242 File "asyncio/coroutines.py", line 141, in coro
243 res = func(*args, **kw)
244 File "test.py", line 5, in bug
245 raise Exception("not consumed")
246 Exception: not consumed
Victor Stinner530ef2f2014-07-08 12:39:10 +0200247
Zachary Ware5819cfa2015-01-06 00:40:43 -0600248There are different options to fix this issue. The first option is to chain the
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100249coroutine in another coroutine and use classic try/except::
250
251 @asyncio.coroutine
252 def handle_exception():
253 try:
254 yield from bug()
255 except Exception:
256 print("exception consumed")
257
258 loop = asyncio.get_event_loop()
259 asyncio.async(handle_exception())
260 loop.run_forever()
261
262Another option is to use the :meth:`BaseEventLoop.run_until_complete`
263function::
264
265 task = asyncio.async(bug())
266 try:
267 loop.run_until_complete(task)
268 except Exception:
269 print("exception consumed")
270
Zachary Ware5819cfa2015-01-06 00:40:43 -0600271.. seealso::
272
273 The :meth:`Future.exception` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100274
275
Zachary Ware5819cfa2015-01-06 00:40:43 -0600276Chain coroutines correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100277--------------------------
278
279When a coroutine function calls other coroutine functions and tasks, they
Eli Bendersky679688e2014-01-20 08:13:31 -0800280should be chained explicitly with ``yield from``. Otherwise, the execution is
281not guaranteed to be sequential.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100282
Eli Bendersky679688e2014-01-20 08:13:31 -0800283Example with different bugs using :func:`asyncio.sleep` to simulate slow
284operations::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100285
286 import asyncio
287
288 @asyncio.coroutine
289 def create():
290 yield from asyncio.sleep(3.0)
291 print("(1) create file")
292
293 @asyncio.coroutine
294 def write():
295 yield from asyncio.sleep(1.0)
296 print("(2) write into file")
297
298 @asyncio.coroutine
299 def close():
300 print("(3) close file")
301
302 @asyncio.coroutine
303 def test():
304 asyncio.async(create())
305 asyncio.async(write())
306 asyncio.async(close())
307 yield from asyncio.sleep(2.0)
308 loop.stop()
309
310 loop = asyncio.get_event_loop()
311 asyncio.async(test())
312 loop.run_forever()
313 print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100314 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100315
316Expected output::
317
318 (1) create file
319 (2) write into file
320 (3) close file
321 Pending tasks at exit: set()
322
323Actual output::
324
325 (3) close file
326 (2) write into file
Victor Stinner530ef2f2014-07-08 12:39:10 +0200327 Pending tasks at exit: {<Task pending create() at test.py:7 wait_for=<Future pending cb=[Task._wakeup()]>>}
328 Task was destroyed but it is pending!
329 task: <Task pending create() done at test.py:5 wait_for=<Future pending cb=[Task._wakeup()]>>
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100330
331The loop stopped before the ``create()`` finished, ``close()`` has been called
332before ``write()``, whereas coroutine functions were called in this order:
333``create()``, ``write()``, ``close()``.
334
335To fix the example, tasks must be marked with ``yield from``::
336
337 @asyncio.coroutine
338 def test():
339 yield from asyncio.async(create())
340 yield from asyncio.async(write())
341 yield from asyncio.async(close())
342 yield from asyncio.sleep(2.0)
343 loop.stop()
344
345Or without ``asyncio.async()``::
346
347 @asyncio.coroutine
348 def test():
349 yield from create()
350 yield from write()
351 yield from close()
352 yield from asyncio.sleep(2.0)
353 loop.stop()
354
Victor Stinner530ef2f2014-07-08 12:39:10 +0200355
356.. _asyncio-pending-task-destroyed:
357
358Pending task destroyed
359----------------------
360
361If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
362<coroutine>` did not complete. It is probably a bug and so a warning is logged.
363
364Example of log::
365
366 Task was destroyed but it is pending!
Victor Stinnerab1c8532014-10-12 21:37:16 +0200367 task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()]>>
Victor Stinner530ef2f2014-07-08 12:39:10 +0200368
369:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
Victor Stinnerab1c8532014-10-12 21:37:16 +0200370traceback where the task was created. Example of log in debug mode::
371
372 Task was destroyed but it is pending!
373 source_traceback: Object created at (most recent call last):
374 File "test.py", line 15, in <module>
375 task = asyncio.async(coro, loop=loop)
376 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>
377
Victor Stinner530ef2f2014-07-08 12:39:10 +0200378
379.. seealso::
380
381 :ref:`Detect coroutine objects never scheduled <asyncio-coroutine-not-scheduled>`.
382
Victor Stinner6a1b0042015-02-04 16:14:33 +0100383.. _asyncio-close-transports:
Victor Stinner188f2c02015-01-30 01:35:14 +0100384
Victor Stinner6a1b0042015-02-04 16:14:33 +0100385Close transports and event loops
386--------------------------------
Victor Stinner188f2c02015-01-30 01:35:14 +0100387
388When a transport is no more needed, call its ``close()`` method to release
Victor Stinner6a1b0042015-02-04 16:14:33 +0100389resources. Event loops must also be closed explicitly.
Victor Stinner188f2c02015-01-30 01:35:14 +0100390
Victor Stinner6a1b0042015-02-04 16:14:33 +0100391If a transport or an event loop is not closed explicitly, a
392:exc:`ResourceWarning` warning will be emitted in its destructor. By default,
393:exc:`ResourceWarning` warnings are ignored. The :ref:`Debug mode of asyncio
394<asyncio-debug-mode>` section explains how to display them.