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
Revert "Add a new async iterable select() function"
Sadly the generator approach doesn't work because of limitations in how
Python handles the `yield` statement and breaking out from a `async for`
for loop (actually this applies to sync generators too).
When the loop is broken, the control is never passed back to the async
genreator, so the `finally` block is never executed (at least not until
the end of the program, where dangling generators are cleared).
Because of this, we will need to use a class instead, and to make it
easy to guarantee avoiding leaking resources (tasks), we make it an
async context managaer and an async iterator.
This reverts commit 2764d01.
Example:
```python
import asyncio
from typing import AsyncIterator
was_gen_finalized: bool = False
async def gen() -> AsyncIterator[int]:
try:
print("gen")
yield 1
finally:
global was_gen_finalized
was_gen_finalized = True
print("gen finally")
async def main() -> None:
global was_gen_finalized
print("1. without break")
async for i in gen():
print(i)
print(f" end of loop: {was_gen_finalized=}")
was_gen_finalized = False
print("------------------")
print("2. with break")
async for i in gen():
print(i)
break
print(f" end of loop: {was_gen_finalized=}")
was_gen_finalized = False
print("------------------")
print("2. with exception")
try:
async for i in gen():
print(i)
raise Exception("Interrupted by exception")
except Exception:
pass
print(f" end of loop: {was_gen_finalized=}")
was_gen_finalized = False
print()
print("END of main")
asyncio.run(main())
print(f"END of asyncio.run(): {was_gen_finalized=}")
```
This program prints:
```
1. without break
gen
1
gen finally
end of loop: was_gen_finalized=True
------------------
2. with break
gen
1
end of loop: was_gen_finalized=False
------------------
2. with exception
gen
1
end of loop: was_gen_finalized=False
END of main
gen finally
gen finally
END of asyncio.run(): was_gen_finalized=True
```
Signed-off-by: Leandro Lucarella <[email protected]>
0 commit comments