yield break in Python

according to answer to this question, yield break in C# is equivalent to return in python. in normal case, 'return' indeed stop a generator. But if your function does nothing but return, you will get a None not an empty iterator, which is returned by yield break in C#

def generate_nothing():
    return

for i in generate_nothing():
    print i

you will get a TypeError: 'NoneType' object is not iterable. but if I add an never run yield before return, this function return what I expect.

def generate_nothing():
    if False: yield None
    return

if works but seems wired. Who has better idea?

thanks,


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.


def generate_nothing():
    return
    yield

def generate_nothing():
    return iter([])
链接地址: http://www.djcxy.com/p/54334.html

上一篇: 在C#中的收益率突破

下一篇: 在Python中产生突破