Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield break in Python

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?

like image 690
Sonic Lee Avatar asked Jun 18 '11 09:06

Sonic Lee


People also ask

What is the yield in Python?

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.

How is yield implemented in Python?

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.

Can you yield multiple times Python?

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.

How do you exit a generator in Python?

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.


1 Answers

def generate_nothing():     return     yield 
like image 170
ninjagecko Avatar answered Sep 20 '22 14:09

ninjagecko