Python 2.7:“有什么东西可以产生吗?”

时间:2012-07-30 22:50:11

标签: python generator yield

在生成器函数中,我怎样才能知道它是否已经产生了什么?

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.'

2 个答案:

答案 0 :(得分:8)

您需要自己保留一个标记,或者在顶部重新构建代码。如果事情太复杂,听起来你的功能可能会做得太多。

此外,如果这是您的消息,则听起来您可能想要例外。

答案 1 :(得分: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。仅当您的生成器从不生成“无”作为其第一个值时才有效:

    ...
    # 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.'