-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdemo.py
50 lines (36 loc) · 1.13 KB
/
demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import asyncio
import contextlib
import taskgroup
import exceptiongroup
class ConnectionClosedError(Exception):
pass
async def poll_database(database):
raise ConnectionClosedError
async def close_connection():
raise ConnectionClosedError
@contextlib.asynccontextmanager
async def database():
try:
yield
finally:
await close_connection()
async def main():
async with taskgroup.timeout(None):
with exceptiongroup.catch({ConnectionClosedError: lambda _: print("done!")}):
async with taskgroup.TaskGroup() as tg:
task = asyncio.current_task()
async with database() as db:
tg.create_task(poll_database(db))
await asyncio.sleep(1)
assert task
print(f"{task.cancelling()=} should be 0")
try:
async with taskgroup.timeout(0.1):
await asyncio.sleep(0.5)
except asyncio.CancelledError:
print("got cancelled incorrectly!")
raise
except TimeoutError:
print("timeout as expected")
asyncio.run(main())
taskgroup.run(main())