Mục Đích Của Yield Python Là Gì ? Yield Trong Python Dùng Để Làm Gì

Want to improve this post? Provide detailed answers lớn this question, including citations & an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
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 = <>, 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 danh mục 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 thả library for metric spaces. This is the liên kết lớn the complete source: <1>.
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
2 Next
To understand what yield does, you must understand what generators are. And before you can underst& generators, you must understvà iterables.

Bạn đang xem: Mục Đích Của Yield Python Là Gì ? Yield Trong Python Dùng Để Làm Gì


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".

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


# 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(), # Loop on candidates (they contain only one element at the beginning)while candidates: # Get the last candidate & remove it from the menu node = candidates.pop() # Get the distance between obj & 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 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:

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.