Debugging AsyncIO

AsyncIO is easier to debug than ReactiveX. It comes with a simple, but very handy, debugging feature. Let's consider the following example:

import asyncio
import time

async def do_something():
print("I do something")
time.sleep(0.5)
print("Done")

loop = asyncio.get_event_loop()
loop.run_until_complete(do_something())
loop.stop()
loop.close()

This example executes a coroutine that prints something, waits for 500 milliseconds, prints something else, and exits. Running the preceding example now gives the following result:

I do something
Done

Everything seems fine, but there is an issue in this code. The debug feature of AsyncIO traps it and prints it. Enabling debug is done for each event loop in the following way:

loop.set_debug(True)

With this line of code added before the event loop is started, the example gives the following result:

I do something
Done
Executing <Task finished coro=<do_something() done, defined at asyncio_debug.py:5> result=None created at /usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py:447> took 0.503 seconds

AsyncIO tells us that the do_something coroutine executed during 500 milliseconds, which is an eternity for the event loop. So it tells us that the blocking call to time.sleep must be replaced by something else. In this case, sleep can be replaced with its asynchronous equivalent:

await asyncio.sleep(0.5)

Now, the example with the debug being enabled does not print this warning again.

The full code for this example is available in the GitHub repository (https://github.com/PacktPublishing/Hands-On-Reactive-Programming-with-Python) of this book, in the asyncio_debug.py script.

Instead of enabling the AsyncIO debug mode for each event loop, it is possible to enable it globally, by setting the PYTHONASYNCIODEBUG environment variable by using the following command:
(venv-rx) $ PYTHONASYNCIODEBUG=1 python3 asyncio_debug.py

The debug mode of AsyncIO monitors the following things:

  • Coroutines that are defined but never awaited
  • Calls to call_soon from a thread other than the event loop
  • Execution time of callbacks and coroutines
  • Resources that are not closed: transports and event loops

This mode is of great help when debugging an issue, and also in ensuring that the behavior is correct. So it is good practice to enable it when testing an application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.182.159