-
Notifications
You must be signed in to change notification settings - Fork 0
/
async_context_manager.py
67 lines (47 loc) · 1.77 KB
/
async_context_manager.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import asyncio
from typing import AsyncContextManager, Optional
from contextlib import AsyncExitStack
class Engine(AsyncContextManager):
def __init__(self):
print(f"{self.__class__} init")
self._stack = AsyncExitStack()
async def __aenter__(self) -> "Engine":
print(f"{self.__class__} enter async context")
return self
async def __aexit__(self, *exc_info):
print(f"{self.__class__} exit async context {exc_info}")
await self._stack.aclose()
async def execute_task(self, count: int):
async with Executor(self) as executor:
async for i in executor.submit(count):
yield i
class Executor(AsyncContextManager):
def __init__(self, _engine: Optional[Engine] = None):
print(f"{self.__class__} init")
self._stack = AsyncExitStack()
self.__standalone = False
if not _engine:
self._engine = Engine()
self.__standalone = True
async def __aenter__(self) -> "Executor":
if self.__standalone:
await self._stack.enter_async_context(self._engine)
print(f"{self.__class__} enter async context")
return self
async def __aexit__(self, *exc_info):
print(f"{self.__class__} exit async context {exc_info}")
await self._stack.aclose()
async def submit(self, count: int):
print(f"{self.__class__} submit")
for i in range(count):
yield i+1
async def main():
print("------------ before -------------")
async with Executor() as one:
async for i in one.submit(5):
print(i)
print("------------ after -------------")
async with Engine() as engine:
async for i in engine.execute_task(5):
print(i)
asyncio.run(main())