1

ジェネレーター関数内で、それがまだ何かを生成したかどうかをどのように知ることができますか?

def my_generator(stuff):
    # complex logic that interprets stuff and may or may not yield anything

    # I only want to yield this if nothing has been yielded yet.
    yield 'Nothing could be done with the input.'
4

2 に答える 2

8

自分でフラグを保持するか、上部のコードを再構築する必要があります。物事が複雑すぎる場合は、関数の機能が多すぎるように思われます。

また、それがあなたのメッセージである場合は、代わりに例外が必要なようです。

于 2012-07-30T22:51:30.780 に答える
2

自分自身を追跡する簡単な方法は、複雑なロジックを内部ジェネレーターにラップすることです。

これの優れている点は、その複雑なロジックを変更する必要がないことです。

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.'
于 2013-12-19T07:48:55.567 に答える