You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Important Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done. For reliable “fire-and-forget” background tasks, gather them in a collection:
Is there a program that proves this behavior to be true? Here's my attempt at showing this behavior:
import asyncio
import gc
async def forever():
while True:
print('forever')
await asyncio.sleep(1)
async def forever_and_one_day():
# From https://docs.python.org/3.10/library/asyncio-task.html#asyncio.create_task :
# "Save a reference to the result of this function, to avoid a task disappearing mid-execution."
# So ... shouldn't it disappear? But it doesn't? When will this hurt?
asyncio.create_task(forever())
while True:
print('and a day')
await asyncio.sleep(1)
gc.collect()
asyncio.run(forever_and_one_day())
However, I ran this example in Python 3.9, 3.10, 3.11 and 3.12 and it continues printing 'forever' and 'and a day' for as long as I care to let it run. According to my interpretation of the docs, it ought to stop printing 'forever', because the result of create_task is not saved anywhere. But it doesn't stop, it just continues.
So what does this documentation actually mean? How do we change this program to exhibit the documented behavior of tasks disappearing mid-execution?
The text was updated successfully, but these errors were encountered:
Documentation
The document for asyncio.create_task - https://docs.python.org/3.10/library/asyncio-task.html#asyncio.create_task - states very plainly:
Is there a program that proves this behavior to be true? Here's my attempt at showing this behavior:
However, I ran this example in Python 3.9, 3.10, 3.11 and 3.12 and it continues printing 'forever' and 'and a day' for as long as I care to let it run. According to my interpretation of the docs, it ought to stop printing 'forever', because the result of create_task is not saved anywhere. But it doesn't stop, it just continues.
So what does this documentation actually mean? How do we change this program to exhibit the documented behavior of tasks disappearing mid-execution?
The text was updated successfully, but these errors were encountered: