Best way to receive the 'return' value from a python generator

后端 未结 4 1757
慢半拍i
慢半拍i 2020-12-15 03:15

Since Python 3.3, if a generator function returns a value, that becomes the value for the StopIteration exception that is raised. This can be collected a number of ways:

4条回答
  •  温柔的废话
    2020-12-15 03:42

    A light-weight way to handle the return value (one that doesn't involve instantiating an auxiliary class) is to use dependency injection.

    Namely, one can pass in the function to handle / act on the return value using the following wrapper / helper generator function:

    def handle_return(generator, func):
        returned = yield from generator
        func(returned)
    

    For example, the following--

    def generate():
        yield 1
        yield 2
        return 3
    
    def show_return(value):
        print('returned: {}'.format(value))
    
    for x in handle_return(generate(), show_return):
        print(x)
    

    results in--

    1
    2
    returned: 3
    

提交回复
热议问题