blob: b728803619297968d9c57fb4f2b8a5e34566de2e [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
Yury Selivanov805e27e2018-09-14 16:57:11 -07005=======================
6Developing with asyncio
7=======================
Victor Stinnerdb39a0d2014-01-16 18:58:01 +01008
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04009Asynchronous programming is different from classic "sequential"
Yury Selivanov805e27e2018-09-14 16:57:11 -070010programming.
11
12This page lists common mistakes and traps and explains how
13to avoid them.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +010014
15
Victor Stinner62511fd2014-06-23 00:36:11 +020016.. _asyncio-debug-mode:
17
Yury Selivanov805e27e2018-09-14 16:57:11 -070018Debug Mode
19==========
Victor Stinner62511fd2014-06-23 00:36:11 +020020
Yury Selivanov805e27e2018-09-14 16:57:11 -070021By default asyncio runs in production mode. In order to ease
22the development asyncio has a *debug mode*.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +020023
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040024There are several ways to enable asyncio debug mode:
Victor Stinnerd71dcbb2014-08-25 17:04:12 +020025
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040026* Setting the :envvar:`PYTHONASYNCIODEBUG` environment variable to ``1``.
Victor Stinner6a1b0042015-02-04 16:14:33 +010027
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040028* Using the :option:`-X` ``dev`` Python command line option.
Victor Stinner62511fd2014-06-23 00:36:11 +020029
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040030* Passing ``debug=True`` to :func:`asyncio.run`.
Yury Selivanov805e27e2018-09-14 16:57:11 -070031
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040032* Calling :meth:`loop.set_debug`.
33
34In addition to enabling the debug mode, consider also:
Yury Selivanov805e27e2018-09-14 16:57:11 -070035
36* setting the log level of the :ref:`asyncio logger <asyncio-logger>` to
37 :py:data:`logging.DEBUG`, for example the following snippet of code
38 can be run at startup of the application::
39
40 logging.basicConfig(level=logging.DEBUG)
41
42* configuring the :mod:`warnings` module to display
43 :exc:`ResourceWarning` warnings. One way of doing that is by
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040044 using the :option:`-W` ``default`` command line option.
Yury Selivanov805e27e2018-09-14 16:57:11 -070045
46
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040047When the debug mode is enabled:
Yury Selivanov805e27e2018-09-14 16:57:11 -070048
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040049* asyncio checks for :ref:`coroutines that were not awaited
50 <asyncio-coroutine-not-scheduled>` and logs them; this mitigates
51 the "forgotten await" pitfall.
Yury Selivanov805e27e2018-09-14 16:57:11 -070052
Benjamin Peterson4e3a53b2018-10-26 10:14:04 -070053* Many non-threadsafe asyncio APIs (such as :meth:`loop.call_soon` and
Yury Selivanov805e27e2018-09-14 16:57:11 -070054 :meth:`loop.call_at` methods) raise an exception if they are called
55 from a wrong thread.
56
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040057* The execution time of the I/O selector is logged if it takes too long to
58 perform an I/O operation.
Yury Selivanov805e27e2018-09-14 16:57:11 -070059
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040060* Callbacks taking longer than 100ms are logged. The
61 :attr:`loop.slow_callback_duration` attribute can be used to set the
62 minimum execution duration in seconds that is considered "slow".
Victor Stinner1077dee2015-01-30 00:55:58 +010063
64
Victor Stinner606ab032014-02-01 03:18:58 +010065.. _asyncio-multithreading:
66
Yury Selivanov805e27e2018-09-14 16:57:11 -070067Concurrency and Multithreading
68==============================
Victor Stinner606ab032014-02-01 03:18:58 +010069
Yury Selivanov7c7605f2018-09-11 09:54:40 -070070An event loop runs in a thread (typically the main thread) and executes
Yury Selivanov805e27e2018-09-14 16:57:11 -070071all callbacks and Tasks in its thread. While a Task is running in the
72event loop, no other Tasks can run in the same thread. When a Task
73executes an ``await`` expression, the running Task gets suspended, and
74the event loop executes the next Task.
Victor Stinner606ab032014-02-01 03:18:58 +010075
Yury Selivanov805e27e2018-09-14 16:57:11 -070076To schedule a callback from a different OS thread, the
Yury Selivanov7c7605f2018-09-11 09:54:40 -070077:meth:`loop.call_soon_threadsafe` method should be used. Example::
Victor Stinner5cb84ed2014-02-04 18:18:27 +010078
Guido van Rossum601953b2015-10-05 16:20:00 -070079 loop.call_soon_threadsafe(callback, *args)
Victor Stinner606ab032014-02-01 03:18:58 +010080
Yury Selivanov805e27e2018-09-14 16:57:11 -070081Almost all asyncio objects are not thread safe, which is typically
82not a problem unless there is code that works with them from outside
83of a Task or a callback. If there's a need for such code to call a
84low-level asyncio API, the :meth:`loop.call_soon_threadsafe` method
85should be used, e.g.::
Victor Stinner790202d2014-02-07 19:03:05 +010086
87 loop.call_soon_threadsafe(fut.cancel)
88
Yury Selivanov805e27e2018-09-14 16:57:11 -070089To schedule a coroutine object from a different OS thread, the
Guido van Rossum601953b2015-10-05 16:20:00 -070090:func:`run_coroutine_threadsafe` function should be used. It returns a
91:class:`concurrent.futures.Future` to access the result::
92
Yury Selivanov805e27e2018-09-14 16:57:11 -070093 async def coro_func():
94 return await asyncio.sleep(1, 42)
95
96 # Later in another OS thread:
97
Guido van Rossum601953b2015-10-05 16:20:00 -070098 future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
Yury Selivanov805e27e2018-09-14 16:57:11 -070099 # Wait for the result:
100 result = future.result()
101
102To handle signals and to execute subprocesses, the event loop must be
103run in the main thread.
Guido van Rossum601953b2015-10-05 16:20:00 -0700104
Carol Willing1abba452018-09-12 22:40:37 -0700105The :meth:`loop.run_in_executor` method can be used with a
Yury Selivanov805e27e2018-09-14 16:57:11 -0700106:class:`concurrent.futures.ThreadPoolExecutor` to execute
107blocking code in a different OS thread without blocking the OS thread
108that the event loop runs in.
Victor Stinner399c59d2015-01-09 01:32:02 +0100109
Victor Stinner606ab032014-02-01 03:18:58 +0100110
Victor Stinner45b27ed2014-02-01 02:36:43 +0100111.. _asyncio-handle-blocking:
112
Yury Selivanov805e27e2018-09-14 16:57:11 -0700113Running Blocking Code
114=====================
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100115
Yury Selivanov805e27e2018-09-14 16:57:11 -0700116Blocking (CPU-bound) code should not be called directly. For example,
117if a function performs a CPU-intensive calculation for 1 second,
118all concurrent asyncio Tasks and IO operations would be delayed
119by 1 second.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100120
Yury Selivanov805e27e2018-09-14 16:57:11 -0700121An executor can be used to run a task in a different thread or even in
122a different process to avoid blocking block the OS thread with the
123event loop. See the :meth:`loop.run_in_executor` method for more
124details.
Victor Stinner45b27ed2014-02-01 02:36:43 +0100125
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100126
127.. _asyncio-logger:
128
Victor Stinner45b27ed2014-02-01 02:36:43 +0100129Logging
Yury Selivanov805e27e2018-09-14 16:57:11 -0700130=======
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100131
Yury Selivanov805e27e2018-09-14 16:57:11 -0700132asyncio uses the :mod:`logging` module and all logging is performed
133via the ``"asyncio"`` logger.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100134
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400135The default log level is :py:data:`logging.INFO`, which can be easily
Yury Selivanov805e27e2018-09-14 16:57:11 -0700136adjusted::
Guido van Rossumba29a4f2016-10-13 13:56:40 -0700137
Yury Selivanov805e27e2018-09-14 16:57:11 -0700138 logging.getLogger("asyncio").setLevel(logging.WARNING)
Guido van Rossumba29a4f2016-10-13 13:56:40 -0700139
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100140
141.. _asyncio-coroutine-not-scheduled:
142
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400143Detect never-awaited coroutines
Yury Selivanov805e27e2018-09-14 16:57:11 -0700144===============================
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100145
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400146When a coroutine function is called, but not awaited
147(e.g. ``coro()`` instead of ``await coro()``)
148or the coroutine is not scheduled with :meth:`asyncio.create_task`, asyncio
149will emit a :exc:`RuntimeWarning`::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100150
151 import asyncio
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100152
Andrew Svetlov88743422017-12-11 17:35:49 +0200153 async def test():
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100154 print("never scheduled")
155
Yury Selivanov805e27e2018-09-14 16:57:11 -0700156 async def main():
157 test()
158
159 asyncio.run(main())
160
161Output::
162
163 test.py:7: RuntimeWarning: coroutine 'test' was never awaited
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100164 test()
165
166Output in debug mode::
167
Yury Selivanov805e27e2018-09-14 16:57:11 -0700168 test.py:7: RuntimeWarning: coroutine 'test' was never awaited
169 Coroutine created at (most recent call last)
170 File "../t.py", line 9, in <module>
171 asyncio.run(main(), debug=True)
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100172
Yury Selivanov805e27e2018-09-14 16:57:11 -0700173 < .. >
Victor Stinner530ef2f2014-07-08 12:39:10 +0200174
Yury Selivanov805e27e2018-09-14 16:57:11 -0700175 File "../t.py", line 7, in main
176 test()
177 test()
Victor Stinner530ef2f2014-07-08 12:39:10 +0200178
Yury Selivanov805e27e2018-09-14 16:57:11 -0700179The usual fix is to either await the coroutine or call the
180:meth:`asyncio.create_task` function::
181
182 async def main():
183 await test()
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100184
185
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400186Detect never-retrieved exceptions
187=================================
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100188
Yury Selivanov805e27e2018-09-14 16:57:11 -0700189If a :meth:`Future.set_exception` is called but the Future object is
190never awaited on, the exception would never be propagated to the
191user code. In this case, asyncio would emit a log message when the
192Future object is garbage collected.
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100193
Yury Selivanov805e27e2018-09-14 16:57:11 -0700194Example of an unhandled exception::
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100195
196 import asyncio
197
Yury Selivanov805e27e2018-09-14 16:57:11 -0700198 async def bug():
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100199 raise Exception("not consumed")
200
Yury Selivanov805e27e2018-09-14 16:57:11 -0700201 async def main():
202 asyncio.create_task(bug())
203
204 asyncio.run(main())
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100205
206Output::
207
Victor Stinner530ef2f2014-07-08 12:39:10 +0200208 Task exception was never retrieved
Yury Selivanov805e27e2018-09-14 16:57:11 -0700209 future: <Task finished coro=<bug() done, defined at test.py:3>
210 exception=Exception('not consumed')>
211
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100212 Traceback (most recent call last):
Yury Selivanov805e27e2018-09-14 16:57:11 -0700213 File "test.py", line 4, in bug
Victor Stinnerdb39a0d2014-01-16 18:58:01 +0100214 raise Exception("not consumed")
215 Exception: not consumed
216
Yury Selivanov805e27e2018-09-14 16:57:11 -0700217:ref:`Enable the debug mode <asyncio-debug-mode>` to get the
218traceback where the task was created::
219
220 asyncio.run(main(), debug=True)
221
222Output in debug mode::
Victor Stinnerab1c8532014-10-12 21:37:16 +0200223
224 Task exception was never retrieved
Yury Selivanov805e27e2018-09-14 16:57:11 -0700225 future: <Task finished coro=<bug() done, defined at test.py:3>
226 exception=Exception('not consumed') created at asyncio/tasks.py:321>
227
Victor Stinnerab1c8532014-10-12 21:37:16 +0200228 source_traceback: Object created at (most recent call last):
Yury Selivanov805e27e2018-09-14 16:57:11 -0700229 File "../t.py", line 9, in <module>
230 asyncio.run(main(), debug=True)
231
232 < .. >
233
Victor Stinnerab1c8532014-10-12 21:37:16 +0200234 Traceback (most recent call last):
Yury Selivanov805e27e2018-09-14 16:57:11 -0700235 File "../t.py", line 4, in bug
Victor Stinnerab1c8532014-10-12 21:37:16 +0200236 raise Exception("not consumed")
237 Exception: not consumed