OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

What does the "yield" keyword do in Python?

  • Thread starter Thread starter Alex. S.
  • Start date Start date
A

Alex. S.

Guest
What functionality does the yield keyword in Python provide?

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

Code:
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 this is the caller:

Code:
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

What 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: Module mspace.
<p>What functionality does the <a href="https://docs.python.org/3/reference/simple_stmts.html#yield" rel="noreferrer"><code>yield</code></a> keyword in Python provide?</p>
<p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p>
<pre><code>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
</code></pre>
<p>And this is the caller:</p>
<pre><code>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
</code></pre>
<p>What happens when the method <code>_get_child_candidates</code> is called?
Is a list returned? A single element? Is it called again? When will subsequent calls stop?</p>

<hr />
<sub>
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: <a href="https://well-adjusted.de/~jrspieker/mspace/" rel="noreferrer">Module mspace</a>.</sub>
 
Top