yield break in Python

前端 未结 4 660
北海茫月
北海茫月 2021-01-30 16:18

According to answer to this question, yield break in C# is equivalent to return in Python. In the normal case, return indeed stops a gener

4条回答
  •  有刺的猬
    2021-01-30 16:51

    The funny part is that both functions have the same bytecode. Probably there's a flag that sets to generator when bytecode compiler finds the yield keyword.

    >>> def f():
    ...   return
    
    >>> def g():
    ...   if False: yield 
    #in Python2 you can use 0 instead of False to achieve the same result
    
    
    >>> from dis import dis
    >>> dis(f)
    2           0 LOAD_CONST               0 (None) 
                3 RETURN_VALUE
    >>> dis(g)
    2           0 LOAD_CONST               0 (None) 
                3 RETURN_VALUE
    

提交回复
热议问题