如何在 python 中使用 yield 来延迟条件语句中的评估?

How to use yield in python to defer evaluation in a conditional statement?

我希望在 if 语句中使用 yield 来延迟回调函数的计算。如果我执行以下操作:

def callback(): 
    print "hi yield"

class dicTest(): 
    e = {}

    def eval(self): 
        yield callback()  

并调用:

d = dicTest() 
gen = d.eval()
gen.next() 
gen = d.eval() 
gen.next() 
gen.next()

然后最后一个 gen.next() 生成异常,如预期的那样。但是,我需要这样做:

def callback(): 
    print "hi yield"

class dicTest(): 
    e = {}

    def eval(self, cond): 
        if cond: 
            print "eval true"
        else: 
            yield callback() 

测试如下:

d = dicTest() 
cond = True 
gen = d.eval(cond)
print "next eval" 
gen.next() 
print "next cond"
cond = False 
print "next eval false"
gen = d.eval(cond) 
gen.next() 
gen.next() 

测试结果:

next eval
eval true
Traceback (most recent call last):
  File "little.py", line 43, in <module>
    gen.next() 
StopIteration

为什么会产生异常?如何解决这个问题?

我认为您误解了 yield 的工作原理。 yield returns 一个值但是保存了生成器的状态。因此,下次您调用 gen.next() 时,生成器会从中断处继续。

在你的情况下,当 cond 为真时,你打印了一些东西但实际上从未产生值。我想你想要的是:

if cond: 
    print "eval true"
    yield "" # Some dummy value
yield callback() 

请注意,这里当 cond 为真时,回调前会有一个额外的 yield。生成器必须再调用一次 next 才能使用第一个 yield 并进入回调。