yield
#Python
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator's methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of yield_list to the generator's caller, or None if yield_list is omitted. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator's methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If __next__() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method.
ジェネレーター関数が呼び出されると、ジェネレーターと呼ばれるイテレーターが返されます。そのジェネレーターは、ジェネレーター関数の実行を制御します。実行は、ジェネレーターのメソッドの1つが呼び出された時点で開始されます。その際、実行は最初のyield式まで進み、そこで再び一時停止され、yield_listの値をジェネレーターの呼び出し元に返します。yield_listが省略された場合はNoneを返します。「一時停止」とは、ローカル変数の現在の束縛、命令ポインター、内部評価スタック、および例外処理の状態を含む、すべてのローカル状態が保持されることを意味します。ジェネレーターのメソッドの1つを呼び出して実行を再開すると、関数はyield式が単なる外部呼び出しであるかのように正確に実行を継続できます。再開後のyield式の結果は、実行を再開したメソッドによって異なります。__next__()が使用された場合(通常はforループまたはnext()組み込み関数経由)、結果はNoneになります。一方、send()が使用された場合、結果は当該メソッドに渡された値になります。
DeepL.com(無料版)で翻訳しました。
一言で言うと、yield は、「一時停止付きの return」。
code:分割バッチ処理(例:API送信、DB書き込み)
def batch(data, size):
for i in range(0, len(data), size):
yield datai:i + size
for chunk in batch(large_list, 100):
send_to_api(chunk)
yieldでサブリストを返し、一時停止。次に進むときはその続きから再開
batch(large_list, 100) で large_list を100件ずつに分割した「ジェネレーター」を得る。
yieldにより、全てのチャンクを一度にメモリに載せず、逐次生成する
code:python
from sqlalchemy.orm import Session
from fastapi import Depends
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
SQLAlchemyでよく書くやつ
yield dbで呼び出し元(ルーター関数など)に db を渡す。
関数の実行はここで一時停止し、呼び出し元の処理が終わるのを待つ。
呼び出し元の処理が終了したあと、自動でセッションをクローズ(後処理)