yield break in Python

Sonic Lee picture Sonic Lee · Jun 18, 2011 · Viewed 44.6k times · Source

According to answer to this question, yield break in C# is equivalent to return in Python. In the normal case, return indeed stops 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 and never run yield before return, this function returns what I expect.

def generate_nothing():
    if False: yield None
    return

It works, but seems weird. Do you have a better idea?

Answer

ninjagecko picture ninjagecko · Jun 18, 2011
def generate_nothing():
    return
    yield