teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

4

aioodbc.utils を参考に、コルーチン部分をインスタンス変数に格納。(※ 但し、再利用は不可に振る舞いは変更)

2020/12/19 02:20

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -13,9 +13,13 @@
13
13
  class C:
14
14
  def __init__(self):
15
15
  print("init C")
16
+ self._coro = self._sleep()
16
17
 
18
+ def __del__(self):
19
+ print("del C")
20
+
17
21
  def __await__(self):
18
- return self._sleep().__await__()
22
+ return self._coro.__await__()
19
23
 
20
24
  async def _sleep(self):
21
25
  await asyncio.sleep(1)

3

説明が正確ではなかったので修正。await では使えるが(awaitable)、create_task 等には渡せない。(not-coroutine)

2020/12/19 02:20

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -3,7 +3,7 @@
3
3
  具体的なコードがないので、状況次第ですが
4
4
 
5
5
  `__await__` メソッドを実装するではだめですか?
6
- オブジェクトをコルーチンとして振る舞わせることは可能です。
6
+ オブジェクトをコルーチン~~として~~のように振る舞わせることは可能です。
7
7
 
8
8
  ----
9
9
 

2

説明補足、__await__ 実装のサンプルコード

2020/12/18 10:32

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -21,7 +21,8 @@
21
21
  await asyncio.sleep(1)
22
22
 
23
23
  async def main():
24
- await C()
24
+ await C() # <--- コンストラクタに async,await は使えないが、
25
+ # __await__ を実装する事で、オブジェクト自身を awaitable に
25
26
  print("DONE")
26
27
 
27
28
 

1

サンプルコードを追加

2020/12/18 05:23

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -3,4 +3,28 @@
3
3
  具体的なコードがないので、状況次第ですが
4
4
 
5
5
  `__await__` メソッドを実装するではだめですか?
6
- オブジェクトをコルーチンとして振る舞わせることは可能です。
6
+ オブジェクトをコルーチンとして振る舞わせることは可能です。
7
+
8
+ ----
9
+
10
+ ```python
11
+ import asyncio
12
+
13
+ class C:
14
+ def __init__(self):
15
+ print("init C")
16
+
17
+ def __await__(self):
18
+ return self._sleep().__await__()
19
+
20
+ async def _sleep(self):
21
+ await asyncio.sleep(1)
22
+
23
+ async def main():
24
+ await C()
25
+ print("DONE")
26
+
27
+
28
+ if __name__ == "__main__":
29
+ asyncio.run(main())
30
+ ```