What does the keyword "yield" do?

For discussions about programming, and for programming questions and advice


Moderator: Forum moderators

Post Reply
KalamyQ
Posts: 16
Joined: Wed Jul 13, 2022 10:59 am
Has thanked: 3 times

What does the keyword "yield" do?

Post 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?

some1
Posts: 71
Joined: Wed Aug 19, 2020 4:32 am
Has thanked: 17 times
Been thanked: 11 times

Re: What does the keyword "yield" do?

Post by some1 »

Websearch "python yield"

Post Reply

Return to “Programming”