-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync_context_manager_dual.py
74 lines (49 loc) · 1.38 KB
/
async_context_manager_dual.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
66
67
68
69
70
71
72
import asyncio
from contextlib import asynccontextmanager
from typing import AsyncContextManager
class ACM(AsyncContextManager):
__already_entered = False
def __init__(self):
print(f"{self} init")
def __repr__(self):
return f"{self.__class__.__name__}"
async def __aenter__(self) -> "ACM":
if self.__already_entered:
return self
self.__already_entered = True
print(f"{self} enter async context")
return self
async def __aexit__(self, *exc_info):
print(f"{self} exit async context {exc_info}")
return True
async def close(self):
await self.__aexit__()
class Foo(ACM):
def __init__(self, name):
self.name = name
super().__init__()
def __repr__(self):
return f"{super().__repr__()}: {self.name}"
class Bar:
@staticmethod
async def create_foo(name):
foo = Foo(name)
await foo.__aenter__()
return foo
@staticmethod
def foo(name):
return Foo(name)
async def main():
bar = Bar()
async with await bar.create_foo(1) as foo:
print(foo)
raise Exception()
print("----------------")
async with bar.foo(2) as foo:
print(foo)
raise Exception()
print("----------------")
foo = await bar.create_foo(3)
print(foo)
await foo.close()
asyncio.run(main())