How to inspect program state in the presence of generators/coroutines?
<p>With normal functions calls, the program state is mostly described by a simple call stack. It is printed out as a traceback after an uncaught exception, it can be examined with <code>inspect.stack</code>, and it can be displayed in a debugger after a breakpoint.</p>

<p>In the presence of generators, generator-based couroutines, and <code>async def</code>-based coroutines, I don't think the call stack is enough. What's a good way to mentally visualize the program state? How do I inspect it in run-time?</p>

<p>There are functions <code>inspect.getgeneratorstate</code> and <code>inspect.getcoroutinestate</code>, but they only provide information about whether the generator/coroutine is created, running, suspended, or closed. In the case the state is <code>RUNNING</code>, I want to be able to examine the actual line number the generator or coroutine is currently executing and the stack frames that correspond to the other functions it might have called. In the case it's <code>SUSPENDED</code>, I want to examine other generators / coroutines it sent data to or yielded to.</p>

<p>Edit: I found a related <a href="http://stackoverflow.com/questions/8389812/how-are-generators-and-coroutines-implemented-in-cpython">question on SO</a> which pointed me to this <a href="http://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html" rel="nofollow">excellent article</a> that explains everything I asked about in this question.</p>

<p>You just have to findout all instances fo generators and co-routines, in all "traditional" frames - (either search for them recursively in all objects in all frames, or you mitght try to use the garbage collector (gc)  module to get a reference to all these instances)</p>

<p>Generators and co-routines have, respectively, a gi_frame and a cr_frame attribute.</p>

python python-3.x python-asyncio coroutine python-internals