Skip to content

Instantly share code, notes, and snippets.

@jorenham
Created February 9, 2021 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorenham/58ccab323710cef2f096aa6f9b968444 to your computer and use it in GitHub Desktop.
Save jorenham/58ccab323710cef2f096aa6f9b968444 to your computer and use it in GitHub Desktop.
demonstration of why asyncio.shield is misleading
import asyncio
async def task():
print('task start')
await asyncio.sleep(.5)
print('task done')
async def run_tasks():
while True:
await asyncio.shield(task())
async def main():
loop = asyncio.get_running_loop()
task_runner = loop.create_task(run_tasks())
await asyncio.sleep(.75)
task_runner.cancel()
await task_runner
# expectation: 'task done' is always printed because of asyncio.shield
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment