Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
What is the use of the yield keyword in Python? What does it do?

For example, I”m trying to understand this code1:

def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance – max_dist = self._median: yield self._rightchild And this is the caller:

result, candidates = <>, while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance = min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))return resultWhat happens when the method _get_child_candidates is called?Is a list returned? A single element? Is it called again? When will subsequent calls stop?

1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: <1>.
python iterator generator yield coroutine
Share
Improve this question
Follow
edited Jun 12 at 19:47

*

BuddyBob
5,32011 gold badge88 silver badges2929 bronze badges
asked Oct 23 “08 at 22:21

*

Alex. S.Alex. S.
128k1616 gold badges5050 silver badges6161 bronze badges
1
Add a comment |

40 Answers 40

Active Oldest Votes
1
2 Next
16022
+600
To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.

Đang xem: Mục Đích của yield python là gì, yield trong python dùng Để làm gì

Iterables

When you create a list, you can read its items one by one. Reading its items one by one is called iteration:

These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.

Generators

Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly:

Yield

yield is a keyword that is used like return, except the function will return a generator.

To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky.

Then, your code will continue from where it left off each time for uses the generator.

Now the hard part:

The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it”ll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting yield. That can be because the loop has come to an end, or because you no longer satisfy an “if/else”.

Xem thêm: Work Out Là Gì Trong Thể Hình? Street Workout Là Gì Work Out Là Gì Trong Thể Hình

Your code explained

Generator:

# Here you create the method of the node object that will return the generatordef _get_child_candidates(self, distance, min_dist, max_dist): # Here is the code that will be called each time you use the generator object: # If there is still a child of the node object on its left # AND if the distance is ok, return the next child if self._leftchild and distance – max_dist = self._median: yield self._rightchild # If the function arrives here, the generator will be considered empty # there is no more than two values: the left and the right childrenCaller:

# Create an empty list and a list with the current object referenceresult, candidates = list(), # Loop on candidates (they contain only one element at the beginning)while candidates: # Get the last candidate and remove it from the list node = candidates.pop() # Get the distance between obj and the candidate distance = node._get_dist(obj) # If distance is ok, then you can fill the result if distance = min_dist: result.extend(node._values) # Add the children of the candidate in the candidate”s list # so the loop will keep running until it will have looked # at all the children of the children of the children, etc. of the candidate candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))return resultThis code contains several smart parts:

The loop iterates on a list, but the list expands while the loop is being iterated. It”s a concise way to go through all these nested data even if it”s a bit dangerous since you can end up with an infinite loop. In this case, candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) exhaust all the values of the generator, but while keeps creating new generator objects which will produce different values from the previous ones since it”s not applied on the same node.

The extend() method is a list object method that expects an iterable and adds its values to the list.

Usually we pass a list to it:

You don”t need to read the values twice.You may have a lot of children and you don”t want them all stored in memory.

And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question…

You can stop here, or read a little bit to see an advanced use of a generator:

Controlling a generator exhaustion

It can be useful for various things like controlling access to a resource.

Itertools, your best friend

The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator?Chain two generators? Group values in a nested list with a one-liner? Map / Zip without creating another list?

Then just import itertools.

Xem thêm: ” Spot Market Là Gì ? Nên Trade Thị Trường Nào: Spot Hay Futures?

An example? Let”s see the possible orders of arrival for a four-horse race:

Understanding the inner mechanisms of iteration

Iteration is a process implying iterables (implementing the __iter__() method) and iterators (implementing the __next__() method).Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.

Leave a Reply

Your email address will not be published. Required fields are marked *