Page 1 of 1

What does the keyword "yield" do?

Posted: Wed Dec 07, 2022 8:50 am
by KalamyQ

What does the yield keyword do in Python? What exactly does it do?
For example, I'm attempting to comprehend the following code1 from this library:

Code: Select all

def _get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild  

And now for the caller:

Code: Select all

result, candidates = [], [self]
while candidates:
    node = candidates.pop()
    distance = node._get_dist(obj)
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

To grasp what yield does, I searched the internet for generators and came across this article, but I couldn't understand it well.
What occurs when the _get child candidates method is called? Is there a list returned? A single component? Is it being called again? When will the phone calls stop?


Re: What does the keyword "yield" do?

Posted: Thu Dec 08, 2022 12:52 pm
by some1

Websearch "python yield"