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?
Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator.
The yield instruction takes the current executing context as a closure, and transforms it into an own living object. This object has a __iter__ method which will continue after this yield statement. So the call stack gets transformed into a heap object.
Conclusion. Like other programming languages, Python can return a single value, but in this, we can use yield statements to return more than one value for the function. The function that uses the yield keyword is known as a generator function.
A better way to end the iterations is by using . close() . In this case, the generator stopped and we left the loop without raising any exception.
def generate_nothing(): return yield
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With