自分自身を追跡する簡単な方法は、複雑なロジックを内部ジェネレーターにラップすることです。
これの優れている点は、その複雑なロジックを変更する必要がないことです。
def my_generator(stuff):
def inner_generator():
# complex logic that interprets stuff and may or may not yield anything
if stuff:
yield 11 * stuff
# I only want to yield this if nothing has been yielded yet.
have_yielded = False
for x in inner_generator():
have_yielded = True
yield x
if not have_yielded:
yield 'Nothing could be done with the input.'
テスト#1:
print(list(my_generator(1)))
=>
[11]
テスト#2:
print(list(my_generator(None)))
=>
['Nothing could be done with the input.']
---代替案---
より複雑なコード、それはおそらく時期尚早の最適化です。have_yieldedをTrueに繰り返し設定することを避けます。ジェネレータが最初の値として「None」を生成しない場合にのみ機能します。
...
# I only want to yield this if nothing has been yielded yet.
have_yielded = False
g = inner_generator()
x = next(g, None)
if x is not None:
yield x
have_yielded = True
for x in g:
yield x
if not have_yielded:
yield 'Nothing could be done with the input.'