【问题标题】:Python 2.7: "Has anything been yielded?"Python 2.7:“有什么产出了吗?”
【发布时间】:2012-07-30 22:50:10
【问题描述】:

在生成器函数中,我怎样才能知道它是否已经产生了任何东西?

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

【问题讨论】:

    标签: python generator yield


    【解决方案1】:

    您需要自己保留一个标志,或重新构造顶部的代码。如果事情太复杂,听起来你的函数可能做的太多了。

    另外,如果这是您的信息,听起来您可能想要一个例外。

    【讨论】:

    • 对于异常的想法也是 +1,但我使用的特定生成器函数是 WSGI 的 application(相当于 C 的 main),除此之外我不能写任何异常- 处理逻辑。听起来 Python 根本没有原生方法让生成器找出它是否产生了任何东西。
    【解决方案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.'
    

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 2017-12-04
      • 2012-04-09
      • 2017-06-22
      • 2014-06-13
      • 2011-06-17
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多