Is it possible to await
arbitrary calls to an async
function when inside a Python debugger?
Say I have the following code in some main.py
file:
import asyncio
async def bar(x):
return x + 1
async def foo():
import ipdb; ipdb.set_trace()
asyncio.run(foo())
Now I want to test calling bar()
with some argument inside the debugger to test the results. The following happens:
$ python3 main.py
> /Users/user/test/main.py(8)foo()
7 import ipdb; ipdb.set_trace()
----> 8 return None
9
ipdb> bar(1)
<coroutine object bar at 0x10404ae60>
main.py:1: RuntimeWarning: coroutine 'bar' was never awaited
import asyncio
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
ipdb> await bar(1)
*** SyntaxError: 'await' outside function
Of course, I can get around this by having x = await bar(1)
above my ipdb.set_trace()
, and then inspecting the results, but then I can't try calling my functions in real time while the debugger is active.
bar(1)
, you need to allow control to return to the event loop, pick up your task from the queue, and run it. The debugger can't do that while leaving your current call stack in place. It seems like you should be able to create a new, private event loop and use that, but asyncio won't let you invoke another event loop while one is already running – Emberipdb
interpreter waiting for our input, and it makes sense. I wishipdb
had a utility function to do this somehow. – Homerhomere