yield break in Python

前端 未结 4 626
北海茫月
北海茫月 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:31
    def generate_nothing():
        return iter([])
    
    0 讨论(0)
  • 2021-01-30 16:46

    A good way to handle this is raising StopIteration which is what is raised when your iterator has nothing left to yield and next() is called. This will also gracefully break out of a for loop with nothing inside the loop executed.

    For example, given a tuple (0, 1, 2, 3) I want to get overlapping pairs ((0, 1), (1, 2), (2, 3)). I could do it like so:

    def pairs(numbers):
        if len(numbers) < 2:
            raise StopIteration
    
        for i, number in enumerate(numbers[1:]):
            yield numbers[i], number
    

    Now pairs safely handles lists with 1 number or less.

    0 讨论(0)
  • 2021-01-30 16:47
    def generate_nothing():
        return
        yield
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题