blob: 2b3ad9417bc928e502ca87cbfb50681f992b795b [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
17To enable the debug mode globally, set the environment variable
18:envvar:`PYTHONASYNCIODEBUG` to ``1``. Examples of effects of the debug mode:
19
20* Log :ref:`coroutines defined but never "yielded from"
21 <asyncio-coroutine-not-scheduled>`
22* :meth:`~BaseEventLoop.call_soon` and :meth:`~BaseEventLoop.call_at` methods
23 raise an exception if they are called from the wrong thread.
24* Log the execution time of the selector
25* Log callbacks taking more than 100 ms to be executed. The
26 :attr:`BaseEventLoop.slow_callback_duration` attribute is the minimum
27 duration in seconds of "slow" callbacks.
28
29.. seealso::
30
31 The :meth:`BaseEventLoop.set_debug` method and the :ref:`asyncio logger
32 <asyncio-logger>`.
33
34
Victor Stinner606ab032014-02-01 03:18:58 +010035.. _asyncio-multithreading:
36
37Concurrency and multithreading
38------------------------------
39
40An event loop runs in a thread and executes all callbacks and tasks in the same
Victor Stinner86516d92014-02-18 09:22:00 +010041thread. While a task is running in the event loop, no other task is running in
Victor Stinner5cb84ed2014-02-04 18:18:27 +010042the same thread. But when the task uses ``yield from``, the task is suspended
43and the event loop executes the next task.
Victor Stinner606ab032014-02-01 03:18:58 +010044
Victor Stinner5cb84ed2014-02-04 18:18:27 +010045To schedule a callback from a different thread, the
46:meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example to
Guido van Rossum3c9bb692014-02-04 13:49:34 -080047schedule a coroutine from a different thread::
Victor Stinner5cb84ed2014-02-04 18:18:27 +010048
49 loop.call_soon_threadsafe(asyncio.async, coro_func())
Victor Stinner606ab032014-02-01 03:18:58 +010050
Victor Stinner790202d2014-02-07 19:03:05 +010051Most asyncio objects are not thread safe. You should only worry if you access
52objects outside the event loop. For example, to cancel a future, don't call
53directly its :meth:`Future.cancel` method, but::
54
55 loop.call_soon_threadsafe(fut.cancel)
56
Victor Stinner606ab032014-02-01 03:18:58 +010057To handle signals and to execute subprocesses, the event loop must be run in
58the main thread.
59
60The :meth:`BaseEventLoop.run_in_executor` method can be used with a thread pool
61executor to execute a callback in different thread to not block the thread of
62the event loop.
63
64.. seealso::
65
66 See the :ref:`Synchronization primitives <asyncio-sync>` section to
67 synchronize tasks.
68
69
Victor Stinner45b27ed2014-02-01 02:36:43 +010070.. _asyncio-handle-blocking:
71
Eli Benderskyb73c8332014-02-09 06:07:47 -080072Handle blocking functions correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010073-----------------------------------
74
75Blocking functions should not be called directly. For example, if a function
76blocks for 1 second, other tasks are delayed by 1 second which can have an
77important impact on reactivity.
78
79For networking and subprocesses, the :mod:`asyncio` module provides high-level
Victor Stinner9592edb2014-02-02 15:03:02 +010080APIs like :ref:`protocols <asyncio-protocol>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010081
82An executor can be used to run a task in a different thread or even in a
83different process, to not block the thread of the event loop. See the
Victor Stinner606ab032014-02-01 03:18:58 +010084:meth:`BaseEventLoop.run_in_executor` method.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010085
Victor Stinner45b27ed2014-02-01 02:36:43 +010086.. seealso::
87
88 The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the
89 event loop handles time.
90
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010091
92.. _asyncio-logger:
93
Victor Stinner45b27ed2014-02-01 02:36:43 +010094Logging
95-------
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010096
Victor Stinner45b27ed2014-02-01 02:36:43 +010097The :mod:`asyncio` module logs information with the :mod:`logging` module in
98the logger ``'asyncio'``.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010099
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100100
101.. _asyncio-coroutine-not-scheduled:
102
103Detect coroutine objects never scheduled
104----------------------------------------
105
106When a coroutine function is called but not passed to :func:`async` or to the
107:class:`Task` constructor, it is not scheduled and it is probably a bug.
108
Victor Stinner62511fd2014-06-23 00:36:11 +0200109To detect such bug, :ref:`enable the debug mode of asyncio
110<asyncio-debug-mode>`. When the coroutine object is destroyed by the garbage
111collector, a log will be emitted with the traceback where the coroutine
112function was called. See the :ref:`asyncio logger <asyncio-logger>`.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100113
114The debug flag changes the behaviour of the :func:`coroutine` decorator. The
Victor Stinner97311832014-01-17 10:31:02 +0100115debug flag value is only used when then coroutine function is defined, not when
116it is called. Coroutine functions defined before the debug flag is set to
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100117``True`` will not be tracked. For example, it is not possible to debug
118coroutines defined in the :mod:`asyncio` module, because the module must be
119imported before the flag value can be changed.
120
121Example with the bug::
122
123 import asyncio
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100124
125 @asyncio.coroutine
126 def test():
127 print("never scheduled")
128
129 test()
130
131Output in debug mode::
132
133 Coroutine 'test' defined at test.py:4 was never yielded from
134
135The fix is to call the :func:`async` function or create a :class:`Task` object
136with this coroutine object.
137
138
139Detect exceptions not consumed
140------------------------------
141
142Python usually calls :func:`sys.displayhook` on unhandled exceptions. If
143:meth:`Future.set_exception` is called, but the exception is not consumed,
144:func:`sys.displayhook` is not called. Instead, a log is emitted when the
145future is deleted by the garbage collector, with the traceback where the
146exception was raised. See the :ref:`asyncio logger <asyncio-logger>`.
147
148Example of unhandled exception::
149
150 import asyncio
151
152 @asyncio.coroutine
153 def bug():
154 raise Exception("not consumed")
155
156 loop = asyncio.get_event_loop()
157 asyncio.async(bug())
158 loop.run_forever()
159
160Output::
161
162 Future/Task exception was never retrieved:
163 Traceback (most recent call last):
164 File "/usr/lib/python3.4/asyncio/tasks.py", line 279, in _step
165 result = next(coro)
166 File "/usr/lib/python3.4/asyncio/tasks.py", line 80, in coro
167 res = func(*args, **kw)
168 File "test.py", line 5, in bug
169 raise Exception("not consumed")
170 Exception: not consumed
171
172There are different options to fix this issue. The first option is to chain to
173coroutine in another coroutine and use classic try/except::
174
175 @asyncio.coroutine
176 def handle_exception():
177 try:
178 yield from bug()
179 except Exception:
180 print("exception consumed")
181
182 loop = asyncio.get_event_loop()
183 asyncio.async(handle_exception())
184 loop.run_forever()
185
186Another option is to use the :meth:`BaseEventLoop.run_until_complete`
187function::
188
189 task = asyncio.async(bug())
190 try:
191 loop.run_until_complete(task)
192 except Exception:
193 print("exception consumed")
194
195See also the :meth:`Future.exception` method.
196
197
Eli Bendersky679688e2014-01-20 08:13:31 -0800198Chain coroutines correctly
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100199--------------------------
200
201When a coroutine function calls other coroutine functions and tasks, they
Eli Bendersky679688e2014-01-20 08:13:31 -0800202should be chained explicitly with ``yield from``. Otherwise, the execution is
203not guaranteed to be sequential.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100204
Eli Bendersky679688e2014-01-20 08:13:31 -0800205Example with different bugs using :func:`asyncio.sleep` to simulate slow
206operations::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100207
208 import asyncio
209
210 @asyncio.coroutine
211 def create():
212 yield from asyncio.sleep(3.0)
213 print("(1) create file")
214
215 @asyncio.coroutine
216 def write():
217 yield from asyncio.sleep(1.0)
218 print("(2) write into file")
219
220 @asyncio.coroutine
221 def close():
222 print("(3) close file")
223
224 @asyncio.coroutine
225 def test():
226 asyncio.async(create())
227 asyncio.async(write())
228 asyncio.async(close())
229 yield from asyncio.sleep(2.0)
230 loop.stop()
231
232 loop = asyncio.get_event_loop()
233 asyncio.async(test())
234 loop.run_forever()
235 print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
Victor Stinnerf40c6632014-01-28 23:32:40 +0100236 loop.close()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100237
238Expected output::
239
240 (1) create file
241 (2) write into file
242 (3) close file
243 Pending tasks at exit: set()
244
245Actual output::
246
247 (3) close file
248 (2) write into file
249 Pending tasks at exit: {Task(<create>)<PENDING>}
250
251The loop stopped before the ``create()`` finished, ``close()`` has been called
252before ``write()``, whereas coroutine functions were called in this order:
253``create()``, ``write()``, ``close()``.
254
255To fix the example, tasks must be marked with ``yield from``::
256
257 @asyncio.coroutine
258 def test():
259 yield from asyncio.async(create())
260 yield from asyncio.async(write())
261 yield from asyncio.async(close())
262 yield from asyncio.sleep(2.0)
263 loop.stop()
264
265Or without ``asyncio.async()``::
266
267 @asyncio.coroutine
268 def test():
269 yield from create()
270 yield from write()
271 yield from close()
272 yield from asyncio.sleep(2.0)
273 loop.stop()
274