Python `yield from`, or return a generator?

后端 未结 5 1513
长发绾君心
长发绾君心 2020-12-28 13:29

I wrote this simple piece of code:

def mymap(func, *seq):
  return (func(*args) for args in zip(*seq))

Should I use the \'return\' statemen

5条回答
  •  一生所求
    2020-12-28 13:59

    The most important difference (I don't know if yield from generator is optimized) is that the context is different for return and yield from.

    
    [ins] In [1]: def generator():
             ...:     yield 1
             ...:     raise Exception
             ...:
    
    [ins] In [2]: def use_generator():
             ...:     return generator()
             ...:
    
    [ins] In [3]: def yield_generator():
             ...:     yield from generator()
             ...:
    
    [ins] In [4]: g = use_generator()
    
    [ins] In [5]: next(g); next(g)
    ---------------------------------------------------------------------------
    Exception                                 Traceback (most recent call last)
     in 
    ----> 1 next(g); next(g)
    
     in generator()
          1 def generator():
          2     yield 1
    ----> 3     raise Exception
          4
    
    Exception:
    
    [ins] In [6]: g = yield_generator()
    
    [ins] In [7]: next(g); next(g)
    ---------------------------------------------------------------------------
    Exception                                 Traceback (most recent call last)
     in 
    ----> 1 next(g); next(g)
    
     in yield_generator()
          1 def yield_generator():
    ----> 2     yield from generator()
          3
    
     in generator()
          1 def generator():
          2     yield 1
    ----> 3     raise Exception
          4
    
    Exception:
    

提交回复
热议问题