从生成器中的下游函数获取结果

时间:2019-07-10 12:30:47

标签: python callback generator return-value

我正在努力寻找如何在python中实现以下实现的方法:

def a_generator():
    i = 0
    while True:
        yield i
        i += 1
        # if [downstream function returns false]:
        #     break
    cleanup()


def cleanup():
    # Do some cleanup task
    pass


def handle_each_value(i):
    if i > 10:
        return False
    return True


for value in a_generator():
    continue_processing = handle_each_value()
    # Cause the generator to run `cleanup()` if `continue_processing == False`

有没有办法做到这一点,无论是通过回调还是作为生成器?

2 个答案:

答案 0 :(得分:3)

具有generator.close功能:

def a_generator():
    i = 0
    try:
        while True:
            print('yield', i)
            yield i
            i += 1
    finally:
        cleanup()


def cleanup():
    # Do some cleanup task
    print('cleaned up')
    pass


def handle_each_value(i):
    if i > 10:
        return False
    return True

gen = a_generator()
for value in gen:
    continue_processing = handle_each_value(value)
    if not continue_processing:
        gen.close()

示例输出:

yield 0
yield 1
yield 2
yield 3
yield 4
yield 5
yield 6
yield 7
yield 8
yield 9
yield 10
yield 11
cleaned up

答案 1 :(得分:1)

这是一个版本:您可以在生成器内部使用cont = yield i以便从生成器外部获取值(由gen.send(value)发送):

def a_generator():
    i = -1
    while True:
        cont = yield i
        if cont == False:
            break
        i += 1
    cleanup()

def cleanup():
    print("cleanup")

def handle_each_value(i):
    if i > 10:
        return False
    return True

gen = a_generator()
next(gen)  # need to prime the generator in order to call .send()
continue_processing = True
try:
    while True:
        value = gen.send(continue_processing)
        continue_processing = handle_each_value(value)
        print(value)
except StopIteration:
    pass