What is the use of the yield từ khoá 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 = <>,
python iterator generator yield coroutine
Improve sầu this question
edited Jun 12 at 19:47
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
Add a comment |
40 Answers 40
Active sầu Oldest Votes
To understand what yield does, you must understand what generators are. And before you can underst& generators, you must understvà 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 sầu a lot of values.
Generators are iterators, a kind of iterable you can only iterate over once. Generators vày not store all the values in memory, they generate the values on the fly:
yield is a keywords that is used like return, except the function will return a generator.
To master yield, you must understvà that when you điện thoại tư vấn the function, the code you have sầu written in the function body toàn thân 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 điện thoại tư vấn will run another iteration of the loop you have written in the function & 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 khổng lồ an over, or because you no longer satisfy an "if/else".
Your code explained
# 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 & 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 & the right childrenCaller:
# Create an empty danh mục & a list with the current object referenceresult, candidates = list(),
The loop iterates on a menu, but the danh mục expands while the loop is being iterated. It"s a concise way to lớn go through all these nested data even if it"s a bit dangerous since you can over 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 danh mục object method that expects an iterable và adds its values to lớn the list.
Usually we pass a menu to lớn it:You don"t need lớn read the values twice.You may have a lot of children & you don"t want them all stored in memory.
And it works because Pybé does not care if the argument of a method is a list or not. Pyhạn hẹp expects iterables so it will work with strings, lists, tuples, và generators! This is called duchồng typing & is one of the reasons why Python thả is so cool. But this is another story, for another question...
You can stop here, or read a little bit khổng lồ see an advanced use of a generator:
Controlling a generator exhaustion
It can be useful for various things like controlling access lớn a resource.
Itertools, your best friend
The itertools module contains special functions to lớn manipulate iterables. Ever wish khổng lồ 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.
An example? Let"s see the possible orders of arrival for a four-horse race: