Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug async python code?

I was playing around async code lately, when I tried to debug the code in PyCharm I saw some really strange behaviour I think it's because of the underlying architectureimport asyncio. This is the code I'm talking about.

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

It's strange because when I set breakpoint inside the coroutine execution is never breaked and whole code completes running easily besides this I don't get much details of event loop(except some mess in the stack).

So here are my questions

  1. Is there any standards or some good practice on debugging async code?
  2. How to peek into execution flow of event loop?
  3. Why isn't it breaking inside the async function?
like image 938
AviKKi Avatar asked Mar 28 '18 04:03

AviKKi


People also ask

How do I debug async method?

Double-clicking an active or awaiting task shows the async call stack in the Call Stack window. To understand which thread is running a specific task, you can swap between the Parallel Threads and Parallel Tasks windows. You can do this by right-clicking and selecting Go To Thread in the context menu.

How do I use async await in Python?

An async function uses the await keyword to denote a coroutine. When using the await keyword, coroutines release the flow of control back to the event loop. To run a coroutine, we need to schedule it on the event loop. After scheduling, coroutines are wrapped in Tasks as a Future object.

Can you do async in Python?

Since Python 3.5, it is possible to use asynchronism in your scripts. This evolution allowed the use of new keywords async and await along with the new module asyncio. Async and Await were firstly introduced in C#, in order to structure non-blocking code in a similar fashion as you would write blocking code.

Is Python async thread-safe?

The async stuff isn't thread safe because it doesn't need to be. Async code is all occurring in the same thread, so it isn't possible to preempt with another one, context switching only occurs at await calls.


1 Answers

Just to add here as sample here:


async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0) # add breakpoint here and then run it in debug mode
    return x + y

tasks = [compute(x,x) for x in range(10)]
loop = asyncio.get_event_loop()
loop.set_debug(True)
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

like image 190
Snehal Parmar Avatar answered Sep 30 '22 17:09

Snehal Parmar