Created
February 15, 2025 16:04
-
-
Save sjshuck/ba2364703a571b5f551ae42f1868565b to your computer and use it in GitHub Desktop.
Async vs sync inner function closure behavior in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from concurrent.futures import Future, ThreadPoolExecutor | |
import time | |
def sync_main() -> None: | |
futures = list[Future[int]]() | |
with ThreadPoolExecutor() as xtor: | |
for outer_n in [4, 3, 2, 1]: | |
def wait_and_return() -> int: | |
inner_n = outer_n | |
time.sleep(inner_n) | |
return inner_n | |
future = xtor.submit(wait_and_return) | |
futures.append(future) | |
print([future.result() for future in futures]) | |
sync_main() | |
# [4, 3, 2, 1] | |
async def async_main() -> None: | |
tasks = list[asyncio.Task[int]]() | |
async with asyncio.TaskGroup() as task_group: | |
for outer_n in [4, 3, 2, 1]: | |
async def wait_and_return() -> int: | |
inner_n = outer_n | |
await asyncio.sleep(inner_n) | |
return inner_n | |
task = task_group.create_task(wait_and_return()) | |
tasks.append(task) | |
print([task.result() for task in tasks]) | |
asyncio.run(async_main()) | |
# [1, 1, 1, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment