0
0

More than 1 year has passed since last update.

python コルーチンについて

Last updated at Posted at 2022-08-28

コルーチンとは

一次処理を中断して再開できるもの。

ジェネレーターで作るコルーチン

  • ジェネレータの作成・活性化・値送信

# ジェネレータを作成
def g_hello():
    r = yield
    yield r

g = g_hello() # ジェネレータオブジェクトを作成
print(next(g)) # ジェネレータオブジェクトを活性化
result = g.send('peanuts') # ジェネレータオブジェクトに値を送る
print(result)

>>> 
peanuts
  • 受け取った値に対して処理(greet(r))を加えて返すことも可能
def greet(r):
    return f'hello: {r}'

def g_hello():
    r = yield
    # yield r
    yield greet(r)

g = g_hello() # ジェネレータオブジェクトを作成
next(g) # ジェネレータオブジェクトを活性化
result = g.send('peanuts') # ジェネレータオブジェクトに値を送る
print(result)

>>>
hello: peanuts
  • コルーチン
    async def で定義した関数。
import asyncio

async def coro_func():
    """coro_func()はコルーチン関数"""
    return 100

コルーチン関数を呼び出すと、コルーチンオブジェクトが返る。
コルーチン関数を実行するにはイベントループに登録する必要がある。

  • コルーチンオブジェクトとは
    • イベントループに登録することで実行できるオブジェクト
print(coro_func())
>>> 
<coroutine object coro_func at 0x0000018651E63DF0>
C:\work\study\python\python_programming\async_practice.py:7: RuntimeWarning: coroutine 'coro_func' was never awaited
  print(coro_func())
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
  • イベントループの作成方法
loop = asyncio.get_event_loop() # イベントループを作成
  • イベントループへの登録方法
task = loop.create_task(coro) # イベントループにコルーチンを登録しタスクオブジェクトを返す。
  • タスクオブジェクト

    • コルーチンオブジェクトの実行状態を管理するオブジェクト
    • コルーチンオブジェクトをイベントループに登録することで、取得
  • タスクオブジェクトの実行

    • task で指定したタスクオブジェクトが完了するまで、イベントループを実行し続けます。
loop.run_until_complete(task)
  • asyncio.run(coro)
    • あたらしくイベントループを作成して、非同期処理を開始するための関数
    • コルーチンオブジェクトをイベントループに登録し、タスクオブジェクトを作成します。
    • タスクオブジェクトが完了するまでイベントループを実行し続けます。

ジェネレーターコルーチンの例

yield

クラス

NotImplementedError

ユーザ定義の基底クラスにおいて、抽象メソッドが派生クラスでオーバライドされることを要求する場合、この例外を送出しなくてはなりません。

絶対オバーライドしろよって場合には使えばよい

参考:PythonのNotImplementedError

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0