Python asyncio: What Keeps a Coroutine's Locals Alive
A reported difference in object lifetime between two coroutines could not be reproduced on four CPython versions. Here is what actually holds a coroutine's locals, and what asyncio is free to retain.

A Stack Overflow question reports two versions of the same coroutine. A Resource is created and a weakref.ref to it is returned. In one version an await asyncio.sleep(0) sits before the return. In the other the await comes after the return, where it can never run. The asker sees None and a __del__ message from the first version. From the second they see the object still alive, before and after gc.collect().
The question is natural: no module-level name points at the object, so why would the position of an await matter? The accepted answer complicates the premise. On CPython 3.8, 3.12, 3.14 and 3.14t, the answerer got None in all eight cases, so the weakref was dead before gc.collect() ran. The surprising result was not reproduced.
So the useful article is not 'why does moving an await keep objects alive'. It is: what holds a coroutine's locals, when does that hold end, and what can legitimately stretch it? This piece works through that.
What the two variants do to reachability
In both variants the only strong reference to the Resource is the local name resource in the coroutine's frame. The weakref does not count. The caller receives only the weakref, so once the frame stops holding the local, nothing is left.
async def producer():
resource = Resource('A')
reference = weakref.ref(resource)
await asyncio.sleep(0) # variant 1: suspends here, then resumes
return reference
async def producer():
resource = Resource('A')
reference = weakref.ref(resource)
return reference # variant 2: returns immediately
await asyncio.sleep(0) # unreachable, but makes this a coroutineThe unreachable await in variant 2 still makes producer a coroutine function, but it never suspends. Variant 1 suspends once and resumes through the event loop. By the frame-ownership model in the answer, both should end the same way: return finishes the frame, the local is released, and the refcount of the Resource reaches zero. Any difference the asker saw has to come from something other than the frame.
The reference chain, layer by layer
The asker sketches a chain: Python name, coroutine frame, coroutine object, asyncio.Task, event loop. It helps to separate which links are language-level and which are asyncio's.
- Name to object: the local
resourcelives in the frame's storage, not in some separate namespace. - Frame to locals: a suspended coroutine must keep its locals, otherwise it could not resume.
- Coroutine object to frame: reachable from Python as
coro.cr_frame(older code and generators usegi_frame). - Task to coroutine: a Task wraps the coroutine, so a live Task can indirectly keep the frame, and therefore the locals, alive.
- Loop to Task: what the loop itself retains is, per the answer, an asyncio implementation detail.
The first three links are mechanical and easy to reason about. The last two are where lifetime becomes harder to predict, and where the answer says to stop assuming anything.
A return clears the frame synchronously
The answer's central claim is that after the return statement is processed, the frame instance holding resource is destroyed, the refcount hits zero, and the object dies. That is deterministic. It does not wait for a collector pass, which is why the answerer calls the gc.collect() in main redundant.
The return value travels a different path from the locals. Older versions conveyed it in a field of a StopIteration exception, and the answer says newer versions handle it more efficiently internally. Either way, asyncio captures the value and delivers it at the other end of the await expression in the caller. Here that value is the weakref, which does not extend the object's life, so the return path itself retains nothing.
This is also why the asker's first variant printing destroyed: A before the 'after gc' line is expected, and why seeing the object alive in the second variant is what needs explaining.
A suspended coroutine keeps every local
Between suspension and completion the frame holds all of its locals, including ones the rest of the function never touches again. The answer's reasoning is short: it could not be otherwise, or the coroutine could not resume. If variant 1 had held resource across the await, the object would be alive for the whole suspension, even though no later line used it.
You can look at these locals from pure Python. coro.cr_frame.f_locals returns a dictionary of them. The answer notes that this view is only writable from Python 3.13, following PEP 667. Since 3.11 the frame object is created lazily, the first time Python code references it. The underlying data exists regardless; it just is not reachable from Python until you ask.
The same answer demonstrates the consequence with a plain generator: take gen.gi_frame.f_locals while the generator is suspended, and the objects in it stay referenced. The idea is sound: anything that holds the frame or a locals dictionary holds the locals.
Where the cyclic collector fits
The question blends two mechanisms. Reference counting frees an object the moment its count reaches zero. The cyclic garbage collector, which gc.collect() triggers, only matters for objects that reference each other and are cut off from the rest of the program. The answer puts it plainly: the cycle collector does not even know about objects whose refcount has reached zero.
That changes how to read the asker's experiment. Calling gc.collect() and seeing None afterwards does not show the collector reclaimed the object. If the refcount was already zero, the collector had nothing to do. If the object were alive because of a plain strong reference, gc.collect() would never free it either, which matches the second output in the question.
The answer gives a recipe for a case that really does depend on the collector: pass one instance of your resource to a second instance's constructor, then del the first. A genuine cycle needs mutual references, so make the two instances point at each other. Only then is the cyclic collector the thing that releases them.
What asyncio itself may retain
The answer concedes that a Task can indirectly keep locals alive through the coroutine or its frame, but did not see it in any test. If the asker really saw the object survive, it was probably an internal reference held by the event loop implementation.
One detail from the answerer's earlier experiments shows how misleading small tests can be. It can look as if asyncio keeps references to coroutines, with weakrefs starting to vanish at around 2000 instances created. A test with a couple of coroutines never shows that. The answer attributes that number to an internal implementation detail of asyncio. Treat it as an observation from one person's tests, not a documented threshold, and do not build on it.
The answer also mentions an overhaul of asyncio code before the CPython 3.14 release, which fixed bugs affecting concurrent loops in different threads under free threading. It does not claim that overhaul explains the asker's output. It suggests the surviving reference might be a bug related to the coroutine having an await past its return, and that a fix may already be applied and backported. That is speculation, and the answer labels it so.
Debugging without trusting the tooling too much
The asker tried gc.get_referrers(resource) and found the output hard to read. That is expected: the inspection call creates temporary references of its own, and execution machinery holds references you will not see in the Python source. The result is a list of candidates, not a verdict.
The answer's guidance on this is practical rather than clever:
- To keep an object alive, hold a hard reference to it. Do not rely on a weakref, and do not rely on the loop holding a task.
- To have it cleaned up, use the normal pattern. If it is still alive after a task is done and its result consumed, that is a leak worth reporting as a bug.
- If a weakref seems stuck, yield to the loop a few times. The answer expects that to release any frame the loop is holding internally.
- Record the exact Python version when you report anything. The question never states one, and the answerer could not reproduce it on four.
Notice what this implies. There is no documented, implementation-independent way to dump the exact chain asyncio uses. You can inspect cr_frame and f_locals, which are visible in the language, but asyncio's own bookkeeping is not part of the contract.
Language guarantee or CPython behaviour
The answer says the deterministic destruction of a returned frame's locals is guaranteed by the language semantics, and that free threading keeps this deterministic as long as no reference to the object lives in a thread other than the one that created it. In a free-threaded build, references held elsewhere can make destruction asynchronous in that edge case, and the object goes once those references are dropped. That is the answer's claim.
I would be more careful than the answer about the phrase 'guaranteed by language semantics'. The mechanism being relied on, immediate destruction at refcount zero, is how CPython behaves. The answer itself points to a discussion on the official Python discourse about formalising the memory model, including lifecycles, which suggests the formal guarantees are not settled. The practical position is: rely on it for CPython, do not write code that depends on a particular moment of destruction on another implementation, and never depend on what asyncio retains.
Where this reasoning does not fit
First, the thread does not explain the asker's observation. The answer could not reproduce it, the question gives no version, and neither identifies a reference that kept the object alive. Anyone who sees the same result should assume a real strong reference exists somewhere, find it, and not conclude that moving an await alters liveness by itself.
Second, none of this licenses code that expects weakrefs to Tasks or coroutines to remain valid. The answer is blunt: write no code that expects weakrefs to tasks to continue existing without a hard reference held elsewhere. Behaviour that looks like the loop retaining coroutines can change between versions and with the number of objects involved.
Third, __del__ output is a weak test of lifetime. It confirms destruction, but only your own reference-holding code and inspection of cr_frame.f_locals tell you who was holding the object. Test on the interpreter version you ship, preferably more than one, and check the result after completion, not only during suspension.
This article draws on Why can moving an await change whether a Python object remains reachable, even when the object has no explicit strong reference? and an answer to it, on the Stack Exchange network, licensed under CC BY-SA 4.0.
- #Python
- #coroutine frame
- #garbage-collection
- #python-asyncio
- #reference counting
- #weak-references



Comments