Accepted answers
curl --request POST \
--url https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"tagged": [
"python"
]
}
'import requests
url = "https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers"
payload = { "tagged": ["python"] }
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({tagged: ['python']})
};
fetch('https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'tagged' => [
'python'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers"
payload := strings.NewReader("{\n \"tagged\": [\n \"python\"\n ]\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"tagged\": [\n \"python\"\n ]\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"tagged\": [\n \"python\"\n ]\n}"
response = http.request(request)
puts response.read_body{
"count": 1,
"has_more": true,
"observed_at_ms": 1789448650776,
"page": 1,
"q": null,
"quota": {
"backoff_seconds": null,
"max": 300,
"remaining": 293
},
"results": [
{
"accepted_answer": {
"answer_id": 231855,
"body_html": "<p>To understand what <a href=\"https://docs.python.org/3/reference/simple_stmts.html#yield\" rel=\"noreferrer\"><code>yield</code></a> does, you must understand what <em><a href=\"https://docs.python.org/3/glossary.html#term-generator\" rel=\"noreferrer\">generators</a></em> are. And before you can understand generators, you must understand <em><a href=\"https://docs.python.org/3/glossary.html#term-iterable\" rel=\"noreferrer\">iterables</a></em>.</p>\n<h2>Iterables</h2>\n<p>When you create a list, you can read its items one by one. Reading its items one by one is called iteration:</p>\n<pre><code>>>> mylist = [1, 2, 3]\n>>> for i in mylist:\n... print(i)\n1\n2\n3\n</code></pre>\n<p><code>mylist</code> is an <em>iterable</em>. When you use a list comprehension, you create a list, and so an iterable:</p>\n<pre><code>>>> mylist = [x*x for x in range(3)]\n>>> for i in mylist:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>Everything you can use "<code>for... in...</code>" on is an iterable; <code>lists</code>, <code>strings</code>, files...</p>\n<p>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 a lot of values.</p>\n<h2>Generators</h2>\n<p>Generators are <em><a href=\"https://docs.python.org/3/glossary.html#term-iterator\" rel=\"noreferrer\">iterators</a></em>, a kind of iterable <strong>you can only iterate over once</strong>. Generators do not store all the values in memory, <strong>they generate the values on the fly</strong>:</p>\n<pre><code>>>> mygenerator = (x*x for x in range(3))\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>It is just the same except you used <code>()</code> instead of <code>[]</code>. BUT, you <strong>cannot</strong> perform <code>for i in mygenerator</code> a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end after calculating 4, one by one.</p>\n<h2>Yield</h2>\n<p><code>yield</code> is a keyword that is used like <code>return</code>, except the function will return a generator.</p>\n<pre><code>>>> def create_generator():\n... mylist = range(3)\n... for i in mylist:\n... yield i*i\n...\n>>> mygenerator = create_generator() # create a generator\n>>> print(mygenerator) # mygenerator is an object!\n<generator object create_generator at 0xb7555c34>\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.</p>\n<p>To master <code>yield</code>, you must understand that <strong>when you call the function, the code you have written in the function body does not run.</strong> The function only returns the generator object, this is a bit tricky.</p>\n<p>Then, your code will continue from where it left off each time <code>for</code> uses the generator.</p>\n<p>Now the hard part:</p>\n<p>The first time the <code>for</code> calls the generator object created from your function, it will run the code in your function from the beginning until it hits <code>yield</code>, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting <code>yield</code>. That can be because the loop has come to an end, or because you no longer satisfy an <code>"if/else"</code>.</p>\n<hr />\n<h2>Your code explained</h2>\n<p><em>Generator:</em></p>\n<pre><code># Here you create the method of the node object that will return the generator\ndef _get_child_candidates(self, distance, min_dist, max_dist):\n\n # Here is the code that will be called each time you use the generator object:\n\n # If there is still a child of the node object on its left\n # AND if the distance is ok, return the next child\n if self._leftchild and distance - max_dist < self._median:\n yield self._leftchild\n\n # If there is still a child of the node object on its right\n # AND if the distance is ok, return the next child\n if self._rightchild and distance + max_dist >= self._median:\n yield self._rightchild\n\n # If the function arrives here, the generator will be considered empty\n # There are no more than two values: the left and the right children\n</code></pre>\n<p><em>Caller:</em></p>\n<pre><code># Create an empty list and a list with the current object reference\nresult, candidates = list(), [self]\n\n# Loop on candidates (they contain only one element at the beginning)\nwhile candidates:\n\n # Get the last candidate and remove it from the list\n node = candidates.pop()\n\n # Get the distance between obj and the candidate\n distance = node._get_dist(obj)\n\n # If the distance is ok, then you can fill in the result\n if distance <= max_dist and distance >= min_dist:\n result.extend(node._values)\n\n # Add the children of the candidate to the candidate's list\n # so the loop will keep running until it has looked\n # at all the children of the children of the children, etc. of the candidate\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\n\nreturn result\n</code></pre>\n<p>This code contains several smart parts:</p>\n<ul>\n<li><p>The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, <code>candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))</code> exhausts all the values of the generator, but <code>while</code> keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.</p>\n</li>\n<li><p>The <code>extend()</code> method is a list object method that expects an iterable and adds its values to the list.</p>\n</li>\n</ul>\n<p>Usually, we pass a list to it:</p>\n<pre><code>>>> a = [1, 2]\n>>> b = [3, 4]\n>>> a.extend(b)\n>>> print(a)\n[1, 2, 3, 4]\n</code></pre>\n<p>But in your code, it gets a generator, which is good because:</p>\n<ol>\n<li>You don't need to read the values twice.</li>\n<li>You may have a lot of children and you don't want them all stored in memory.</li>\n</ol>\n<p>And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...</p>\n<p>You can stop here, or read a little bit to see an advanced use of a generator:</p>\n<h2>Controlling a generator exhaustion</h2>\n<pre><code>>>> class Bank(): # Let's create a bank, building ATMs\n... crisis = False\n... def create_atm(self):\n... while not self.crisis:\n... yield "$100"\n>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want\n>>> corner_street_atm = hsbc.create_atm()\n>>> print(corner_street_atm.next())\n$100\n>>> print(corner_street_atm.next())\n$100\n>>> print([corner_street_atm.next() for cash in range(5)])\n['$100', '$100', '$100', '$100', '$100']\n>>> hsbc.crisis = True # Crisis is coming, no more money!\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs\n>>> print(wall_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business\n>>> for cash in brand_new_atm:\n... print cash\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n...\n</code></pre>\n<p><strong>Note:</strong> For Python 3, use<code>print(corner_street_atm.__next__())</code> or <code>print(next(corner_street_atm))</code></p>\n<p>It can be useful for various things like controlling access to a resource.</p>\n<h2>Itertools, your best friend</h2>\n<p>The <code>itertools</code> module contains special functions to manipulate iterables. Ever wish to duplicate a generator?\nChain two generators? Group values in a nested list with a one-liner? <code>Map / Zip</code> without creating another list?</p>\n<p>Then just <code>import itertools</code>.</p>\n<p>An example? Let's see the possible orders of arrival for a four-horse race:</p>\n<pre><code>>>> horses = [1, 2, 3, 4]\n>>> races = itertools.permutations(horses)\n>>> print(races)\n<itertools.permutations object at 0xb754f1dc>\n>>> print(list(itertools.permutations(horses)))\n[(1, 2, 3, 4),\n (1, 2, 4, 3),\n (1, 3, 2, 4),\n (1, 3, 4, 2),\n (1, 4, 2, 3),\n (1, 4, 3, 2),\n (2, 1, 3, 4),\n (2, 1, 4, 3),\n (2, 3, 1, 4),\n (2, 3, 4, 1),\n (2, 4, 1, 3),\n (2, 4, 3, 1),\n (3, 1, 2, 4),\n (3, 1, 4, 2),\n (3, 2, 1, 4),\n (3, 2, 4, 1),\n (3, 4, 1, 2),\n (3, 4, 2, 1),\n (4, 1, 2, 3),\n (4, 1, 3, 2),\n (4, 2, 1, 3),\n (4, 2, 3, 1),\n (4, 3, 1, 2),\n (4, 3, 2, 1)]\n</code></pre>\n<h2>Understanding the inner mechanisms of iteration</h2>\n<p>Iteration is a process implying iterables (implementing the <code>__iter__()</code> method) and iterators (implementing the <code>__next__()</code> method).\nIterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.</p>\n<p>There is more about it in this article about <a href=\"https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm\" rel=\"noreferrer\">how <code>for</code> loops work</a>.</p>\n",
"body_markdown": "To understand what [`yield`] does, you must understand what *[generators]* are. And before you can understand generators, you must understand *[iterables]*.\r\n\r\nIterables\r\n---------\r\n\r\nWhen you create a list, you can read its items one by one. Reading its items one by one is called iteration:\r\n\r\n >>> mylist = [1, 2, 3]\r\n >>> for i in mylist:\r\n ... print(i)\r\n 1\r\n 2\r\n 3\r\n\r\n`mylist` is an *iterable*. When you use a list comprehension, you create a list, and so an iterable:\r\n\r\n >>> mylist = [x*x for x in range(3)]\r\n >>> for i in mylist:\r\n ... print(i)\r\n 0\r\n 1\r\n 4\r\n\r\nEverything you can use \"`for... in...`\" on is an iterable; `lists`, `strings`, files...\r\n\r\nThese 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 a lot of values.\r\n\r\nGenerators\r\n----------\r\n\r\nGenerators are *[iterators]*, a kind of iterable **you can only iterate over once**. Generators do not store all the values in memory, **they generate the values on the fly**:\r\n\r\n >>> mygenerator = (x*x for x in range(3))\r\n >>> for i in mygenerator:\r\n ... print(i)\r\n 0\r\n 1\r\n 4\r\n\r\nIt is just the same except you used `()` instead of `[]`. BUT, you **cannot** perform `for i in mygenerator` a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end after calculating 4, one by one.\r\n\r\nYield\r\n-----\r\n\r\n`yield` is a keyword that is used like `return`, except the function will return a generator.\r\n\r\n >>> def create_generator():\r\n ... mylist = range(3)\r\n ... for i in mylist:\r\n ... yield i*i\r\n ...\r\n >>> mygenerator = create_generator() # create a generator\r\n >>> print(mygenerator) # mygenerator is an object!\r\n <generator object create_generator at 0xb7555c34>\r\n >>> for i in mygenerator:\r\n ... print(i)\r\n 0\r\n 1\r\n 4\r\n\r\nHere it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.\r\n\r\nTo master `yield`, you must understand that **when you call the function, the code you have written in the function body does not run.** The function only returns the generator object, this is a bit tricky.\r\n\r\nThen, your code will continue from where it left off each time `for` uses the generator.\r\n\r\nNow the hard part:\r\n\r\nThe 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 call will run another iteration of the loop you have written in the function and 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 to an end, or because you no longer satisfy an `\"if/else\"`.\r\n\r\n---\r\n\r\nYour code explained\r\n-------------------\r\n\r\n*Generator:*\r\n\r\n # Here you create the method of the node object that will return the generator\r\n def _get_child_candidates(self, distance, min_dist, max_dist):\r\n\r\n # Here is the code that will be called each time you use the generator object:\r\n\r\n # If there is still a child of the node object on its left\r\n # AND if the distance is ok, return the next child\r\n if self._leftchild and distance - max_dist < self._median:\r\n yield self._leftchild\r\n\r\n # If there is still a child of the node object on its right\r\n # AND if the distance is ok, return the next child\r\n if self._rightchild and distance + max_dist >= self._median:\r\n yield self._rightchild\r\n\r\n # If the function arrives here, the generator will be considered empty\r\n # There are no more than two values: the left and the right children\r\n\r\n*Caller:*\r\n\r\n # Create an empty list and a list with the current object reference\r\n result, candidates = list(), [self]\r\n\r\n # Loop on candidates (they contain only one element at the beginning)\r\n while candidates:\r\n\r\n # Get the last candidate and remove it from the list\r\n node = candidates.pop()\r\n\r\n # Get the distance between obj and the candidate\r\n distance = node._get_dist(obj)\r\n\r\n # If the distance is ok, then you can fill in the result\r\n if distance <= max_dist and distance >= min_dist:\r\n result.extend(node._values)\r\n\r\n # Add the children of the candidate to the candidate's list\r\n # so the loop will keep running until it has looked\r\n # at all the children of the children of the children, etc. of the candidate\r\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\r\n\r\n return result\r\n\r\nThis code contains several smart parts:\r\n\r\n- The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, `candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))` exhausts 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.\r\n\r\n- The `extend()` method is a list object method that expects an iterable and adds its values to the list.\r\n\r\nUsually, we pass a list to it:\r\n\r\n >>> a = [1, 2]\r\n >>> b = [3, 4]\r\n >>> a.extend(b)\r\n >>> print(a)\r\n [1, 2, 3, 4]\r\n\r\nBut in your code, it gets a generator, which is good because:\r\n\r\n1. You don't need to read the values twice.\r\n2. You may have a lot of children and you don't want them all stored in memory.\r\n\r\nAnd it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...\r\n\r\nYou can stop here, or read a little bit to see an advanced use of a generator:\r\n\r\nControlling a generator exhaustion\r\n------\r\n\r\n >>> class Bank(): # Let's create a bank, building ATMs\r\n ... crisis = False\r\n ... def create_atm(self):\r\n ... while not self.crisis:\r\n ... yield \"$100\"\r\n >>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want\r\n >>> corner_street_atm = hsbc.create_atm()\r\n >>> print(corner_street_atm.next())\r\n $100\r\n >>> print(corner_street_atm.next())\r\n $100\r\n >>> print([corner_street_atm.next() for cash in range(5)])\r\n ['$100', '$100', '$100', '$100', '$100']\r\n >>> hsbc.crisis = True # Crisis is coming, no more money!\r\n >>> print(corner_street_atm.next())\r\n <type 'exceptions.StopIteration'>\r\n >>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs\r\n >>> print(wall_street_atm.next())\r\n <type 'exceptions.StopIteration'>\r\n >>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty\r\n >>> print(corner_street_atm.next())\r\n <type 'exceptions.StopIteration'>\r\n >>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business\r\n >>> for cash in brand_new_atm:\r\n ... print cash\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n ...\r\n\r\n**Note:** For Python 3, use`print(corner_street_atm.__next__())` or `print(next(corner_street_atm))`\r\n\r\nIt can be useful for various things like controlling access to a resource.\r\n\r\nItertools, your best friend\r\n-----\r\n\r\nThe `itertools` module contains special functions to manipulate iterables. Ever wish to duplicate a generator?\r\nChain two generators? Group values in a nested list with a one-liner? `Map / Zip` without creating another list?\r\n\r\nThen just `import itertools`.\r\n\r\nAn example? Let's see the possible orders of arrival for a four-horse race:\r\n\r\n >>> horses = [1, 2, 3, 4]\r\n >>> races = itertools.permutations(horses)\r\n >>> print(races)\r\n <itertools.permutations object at 0xb754f1dc>\r\n >>> print(list(itertools.permutations(horses)))\r\n [(1, 2, 3, 4),\r\n (1, 2, 4, 3),\r\n (1, 3, 2, 4),\r\n (1, 3, 4, 2),\r\n (1, 4, 2, 3),\r\n (1, 4, 3, 2),\r\n (2, 1, 3, 4),\r\n (2, 1, 4, 3),\r\n (2, 3, 1, 4),\r\n (2, 3, 4, 1),\r\n (2, 4, 1, 3),\r\n (2, 4, 3, 1),\r\n (3, 1, 2, 4),\r\n (3, 1, 4, 2),\r\n (3, 2, 1, 4),\r\n (3, 2, 4, 1),\r\n (3, 4, 1, 2),\r\n (3, 4, 2, 1),\r\n (4, 1, 2, 3),\r\n (4, 1, 3, 2),\r\n (4, 2, 1, 3),\r\n (4, 2, 3, 1),\r\n (4, 3, 1, 2),\r\n (4, 3, 2, 1)]\r\n\r\n\r\nUnderstanding the inner mechanisms of iteration\r\n------\r\n\r\nIteration is a process implying iterables (implementing the `__iter__()` method) and iterators (implementing the `__next__()` method).\r\nIterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.\r\n\r\nThere is more about it in this article about [how `for` loops work][1].\r\n\r\n [1]: https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm\r\n\r\n [`yield`]: https://docs.python.org/3/reference/simple_stmts.html#yield\r\n [generators]: https://docs.python.org/3/glossary.html#term-generator\r\n [iterables]: https://docs.python.org/3/glossary.html#term-iterable\r\n [iterators]: https://docs.python.org/3/glossary.html#term-iterator",
"comment_count": 13,
"content_license": "CC BY-SA 4.0",
"created_at_ms": 1224802124000,
"is_accepted": true,
"last_activity_at_ms": 1711253853000,
"last_edit_at_ms": 1711253853000,
"owner": {
"display_name": "Bite code",
"link": "https://stackoverflow.com/users/9951/bite-code",
"reputation": 601941,
"user_id": 9951,
"user_type": "registered"
},
"question_id": 231767,
"question_title": "What does the \"yield\" keyword do in Python?",
"score": 18317,
"site": "stackoverflow",
"source_url": "https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python/231855#231855"
},
"question": {
"accepted_answer_id": 231855,
"answer_count": 51,
"body_html": "<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>\n<p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p>\n<pre><code>def _get_child_candidates(self, distance, min_dist, max_dist):\n if self._leftchild and distance - max_dist < self._median:\n yield self._leftchild\n if self._rightchild and distance + max_dist >= self._median:\n yield self._rightchild \n</code></pre>\n<p>And this is the caller:</p>\n<pre><code>result, candidates = [], [self]\nwhile candidates:\n node = candidates.pop()\n distance = node._get_dist(obj)\n if distance <= max_dist and distance >= min_dist:\n result.extend(node._values)\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\nreturn result\n</code></pre>\n<p>What happens when the method <code>_get_child_candidates</code> is called?\nIs a list returned? A single element? Is it called again? When will subsequent calls stop?</p>\n\n<hr />\n<sub>\n1. 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> \n",
"body_markdown": "What functionality does the [`yield`] keyword in Python provide?\r\n\r\nFor example, I'm trying to understand this code<sup>**1**</sup>:\r\n\r\n def _get_child_candidates(self, distance, min_dist, max_dist):\r\n if self._leftchild and distance - max_dist < self._median:\r\n yield self._leftchild\r\n if self._rightchild and distance + max_dist >= self._median:\r\n yield self._rightchild\t\r\n\r\nAnd this is the caller:\r\n\r\n result, candidates = [], [self]\r\n while candidates:\r\n node = candidates.pop()\r\n distance = node._get_dist(obj)\r\n if distance <= max_dist and distance >= min_dist:\r\n result.extend(node._values)\r\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\r\n return result\r\n\r\nWhat happens when the method `_get_child_candidates` is called?\r\nIs a list returned? A single element? Is it called again? When will subsequent calls stop?\r\n\r\n\r\n[`yield`]: https://docs.python.org/3/reference/simple_stmts.html#yield\r\n\r\n<!-- https://docs.python.org/3/reference/expressions.html#yieldexpr -->\r\n\r\n\r\n----------\r\n\r\n\r\n<sub>\r\n1. 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/\">Module mspace</a>.</sub> ",
"closed_at_ms": null,
"closed_reason": null,
"comment_count": 6,
"content_license": null,
"created_at_ms": 1224800471000,
"is_answered": true,
"last_activity_at_ms": 1777574627000,
"last_edit_at_ms": 1711253482000,
"owner": {
"display_name": "Alex. S.",
"link": "https://stackoverflow.com/users/18300/alex-s",
"reputation": 148444,
"user_id": 18300,
"user_type": "registered"
},
"question_id": 231767,
"score": 13135,
"site": "stackoverflow",
"source_url": "https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python",
"tags": [
"python",
"iterator",
"generator",
"yield"
],
"title": "What does the \"yield\" keyword do in Python?",
"view_count": 3499052
}
}
],
"site": "stackoverflow",
"source_url": "https://api.stackexchange.com/2.3/search/advanced?site=stackoverflow&tagged=python&accepted=true&pagesize=1&sort=votes&filter=%217ry9ouLWcQWrdWSzrv7eT0TX0kxJ.zt0R1",
"tagged": [
"python"
],
"total": 1144387
}Stack Exchange
Accepted answers
Accepted answers by topic: the top questions on one site carrying every tag in tagged (optionally narrowed by q), each paired with its accepted answer. One search call plus one batched answers call; has_more + page paginate.
POST
https://api.aisa.one
/
apis
/
v1
/
stackexchange-com
/
questions
/
accepted-answers
Accepted answers
curl --request POST \
--url https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"tagged": [
"python"
]
}
'import requests
url = "https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers"
payload = { "tagged": ["python"] }
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({tagged: ['python']})
};
fetch('https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'tagged' => [
'python'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers"
payload := strings.NewReader("{\n \"tagged\": [\n \"python\"\n ]\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"tagged\": [\n \"python\"\n ]\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"tagged\": [\n \"python\"\n ]\n}"
response = http.request(request)
puts response.read_body{
"count": 1,
"has_more": true,
"observed_at_ms": 1789448650776,
"page": 1,
"q": null,
"quota": {
"backoff_seconds": null,
"max": 300,
"remaining": 293
},
"results": [
{
"accepted_answer": {
"answer_id": 231855,
"body_html": "<p>To understand what <a href=\"https://docs.python.org/3/reference/simple_stmts.html#yield\" rel=\"noreferrer\"><code>yield</code></a> does, you must understand what <em><a href=\"https://docs.python.org/3/glossary.html#term-generator\" rel=\"noreferrer\">generators</a></em> are. And before you can understand generators, you must understand <em><a href=\"https://docs.python.org/3/glossary.html#term-iterable\" rel=\"noreferrer\">iterables</a></em>.</p>\n<h2>Iterables</h2>\n<p>When you create a list, you can read its items one by one. Reading its items one by one is called iteration:</p>\n<pre><code>>>> mylist = [1, 2, 3]\n>>> for i in mylist:\n... print(i)\n1\n2\n3\n</code></pre>\n<p><code>mylist</code> is an <em>iterable</em>. When you use a list comprehension, you create a list, and so an iterable:</p>\n<pre><code>>>> mylist = [x*x for x in range(3)]\n>>> for i in mylist:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>Everything you can use "<code>for... in...</code>" on is an iterable; <code>lists</code>, <code>strings</code>, files...</p>\n<p>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 a lot of values.</p>\n<h2>Generators</h2>\n<p>Generators are <em><a href=\"https://docs.python.org/3/glossary.html#term-iterator\" rel=\"noreferrer\">iterators</a></em>, a kind of iterable <strong>you can only iterate over once</strong>. Generators do not store all the values in memory, <strong>they generate the values on the fly</strong>:</p>\n<pre><code>>>> mygenerator = (x*x for x in range(3))\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>It is just the same except you used <code>()</code> instead of <code>[]</code>. BUT, you <strong>cannot</strong> perform <code>for i in mygenerator</code> a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end after calculating 4, one by one.</p>\n<h2>Yield</h2>\n<p><code>yield</code> is a keyword that is used like <code>return</code>, except the function will return a generator.</p>\n<pre><code>>>> def create_generator():\n... mylist = range(3)\n... for i in mylist:\n... yield i*i\n...\n>>> mygenerator = create_generator() # create a generator\n>>> print(mygenerator) # mygenerator is an object!\n<generator object create_generator at 0xb7555c34>\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.</p>\n<p>To master <code>yield</code>, you must understand that <strong>when you call the function, the code you have written in the function body does not run.</strong> The function only returns the generator object, this is a bit tricky.</p>\n<p>Then, your code will continue from where it left off each time <code>for</code> uses the generator.</p>\n<p>Now the hard part:</p>\n<p>The first time the <code>for</code> calls the generator object created from your function, it will run the code in your function from the beginning until it hits <code>yield</code>, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting <code>yield</code>. That can be because the loop has come to an end, or because you no longer satisfy an <code>"if/else"</code>.</p>\n<hr />\n<h2>Your code explained</h2>\n<p><em>Generator:</em></p>\n<pre><code># Here you create the method of the node object that will return the generator\ndef _get_child_candidates(self, distance, min_dist, max_dist):\n\n # Here is the code that will be called each time you use the generator object:\n\n # If there is still a child of the node object on its left\n # AND if the distance is ok, return the next child\n if self._leftchild and distance - max_dist < self._median:\n yield self._leftchild\n\n # If there is still a child of the node object on its right\n # AND if the distance is ok, return the next child\n if self._rightchild and distance + max_dist >= self._median:\n yield self._rightchild\n\n # If the function arrives here, the generator will be considered empty\n # There are no more than two values: the left and the right children\n</code></pre>\n<p><em>Caller:</em></p>\n<pre><code># Create an empty list and a list with the current object reference\nresult, candidates = list(), [self]\n\n# Loop on candidates (they contain only one element at the beginning)\nwhile candidates:\n\n # Get the last candidate and remove it from the list\n node = candidates.pop()\n\n # Get the distance between obj and the candidate\n distance = node._get_dist(obj)\n\n # If the distance is ok, then you can fill in the result\n if distance <= max_dist and distance >= min_dist:\n result.extend(node._values)\n\n # Add the children of the candidate to the candidate's list\n # so the loop will keep running until it has looked\n # at all the children of the children of the children, etc. of the candidate\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\n\nreturn result\n</code></pre>\n<p>This code contains several smart parts:</p>\n<ul>\n<li><p>The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, <code>candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))</code> exhausts all the values of the generator, but <code>while</code> keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.</p>\n</li>\n<li><p>The <code>extend()</code> method is a list object method that expects an iterable and adds its values to the list.</p>\n</li>\n</ul>\n<p>Usually, we pass a list to it:</p>\n<pre><code>>>> a = [1, 2]\n>>> b = [3, 4]\n>>> a.extend(b)\n>>> print(a)\n[1, 2, 3, 4]\n</code></pre>\n<p>But in your code, it gets a generator, which is good because:</p>\n<ol>\n<li>You don't need to read the values twice.</li>\n<li>You may have a lot of children and you don't want them all stored in memory.</li>\n</ol>\n<p>And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...</p>\n<p>You can stop here, or read a little bit to see an advanced use of a generator:</p>\n<h2>Controlling a generator exhaustion</h2>\n<pre><code>>>> class Bank(): # Let's create a bank, building ATMs\n... crisis = False\n... def create_atm(self):\n... while not self.crisis:\n... yield "$100"\n>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want\n>>> corner_street_atm = hsbc.create_atm()\n>>> print(corner_street_atm.next())\n$100\n>>> print(corner_street_atm.next())\n$100\n>>> print([corner_street_atm.next() for cash in range(5)])\n['$100', '$100', '$100', '$100', '$100']\n>>> hsbc.crisis = True # Crisis is coming, no more money!\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs\n>>> print(wall_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business\n>>> for cash in brand_new_atm:\n... print cash\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n...\n</code></pre>\n<p><strong>Note:</strong> For Python 3, use<code>print(corner_street_atm.__next__())</code> or <code>print(next(corner_street_atm))</code></p>\n<p>It can be useful for various things like controlling access to a resource.</p>\n<h2>Itertools, your best friend</h2>\n<p>The <code>itertools</code> module contains special functions to manipulate iterables. Ever wish to duplicate a generator?\nChain two generators? Group values in a nested list with a one-liner? <code>Map / Zip</code> without creating another list?</p>\n<p>Then just <code>import itertools</code>.</p>\n<p>An example? Let's see the possible orders of arrival for a four-horse race:</p>\n<pre><code>>>> horses = [1, 2, 3, 4]\n>>> races = itertools.permutations(horses)\n>>> print(races)\n<itertools.permutations object at 0xb754f1dc>\n>>> print(list(itertools.permutations(horses)))\n[(1, 2, 3, 4),\n (1, 2, 4, 3),\n (1, 3, 2, 4),\n (1, 3, 4, 2),\n (1, 4, 2, 3),\n (1, 4, 3, 2),\n (2, 1, 3, 4),\n (2, 1, 4, 3),\n (2, 3, 1, 4),\n (2, 3, 4, 1),\n (2, 4, 1, 3),\n (2, 4, 3, 1),\n (3, 1, 2, 4),\n (3, 1, 4, 2),\n (3, 2, 1, 4),\n (3, 2, 4, 1),\n (3, 4, 1, 2),\n (3, 4, 2, 1),\n (4, 1, 2, 3),\n (4, 1, 3, 2),\n (4, 2, 1, 3),\n (4, 2, 3, 1),\n (4, 3, 1, 2),\n (4, 3, 2, 1)]\n</code></pre>\n<h2>Understanding the inner mechanisms of iteration</h2>\n<p>Iteration is a process implying iterables (implementing the <code>__iter__()</code> method) and iterators (implementing the <code>__next__()</code> method).\nIterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.</p>\n<p>There is more about it in this article about <a href=\"https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm\" rel=\"noreferrer\">how <code>for</code> loops work</a>.</p>\n",
"body_markdown": "To understand what [`yield`] does, you must understand what *[generators]* are. And before you can understand generators, you must understand *[iterables]*.\r\n\r\nIterables\r\n---------\r\n\r\nWhen you create a list, you can read its items one by one. Reading its items one by one is called iteration:\r\n\r\n >>> mylist = [1, 2, 3]\r\n >>> for i in mylist:\r\n ... print(i)\r\n 1\r\n 2\r\n 3\r\n\r\n`mylist` is an *iterable*. When you use a list comprehension, you create a list, and so an iterable:\r\n\r\n >>> mylist = [x*x for x in range(3)]\r\n >>> for i in mylist:\r\n ... print(i)\r\n 0\r\n 1\r\n 4\r\n\r\nEverything you can use \"`for... in...`\" on is an iterable; `lists`, `strings`, files...\r\n\r\nThese 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 a lot of values.\r\n\r\nGenerators\r\n----------\r\n\r\nGenerators are *[iterators]*, a kind of iterable **you can only iterate over once**. Generators do not store all the values in memory, **they generate the values on the fly**:\r\n\r\n >>> mygenerator = (x*x for x in range(3))\r\n >>> for i in mygenerator:\r\n ... print(i)\r\n 0\r\n 1\r\n 4\r\n\r\nIt is just the same except you used `()` instead of `[]`. BUT, you **cannot** perform `for i in mygenerator` a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end after calculating 4, one by one.\r\n\r\nYield\r\n-----\r\n\r\n`yield` is a keyword that is used like `return`, except the function will return a generator.\r\n\r\n >>> def create_generator():\r\n ... mylist = range(3)\r\n ... for i in mylist:\r\n ... yield i*i\r\n ...\r\n >>> mygenerator = create_generator() # create a generator\r\n >>> print(mygenerator) # mygenerator is an object!\r\n <generator object create_generator at 0xb7555c34>\r\n >>> for i in mygenerator:\r\n ... print(i)\r\n 0\r\n 1\r\n 4\r\n\r\nHere it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.\r\n\r\nTo master `yield`, you must understand that **when you call the function, the code you have written in the function body does not run.** The function only returns the generator object, this is a bit tricky.\r\n\r\nThen, your code will continue from where it left off each time `for` uses the generator.\r\n\r\nNow the hard part:\r\n\r\nThe 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 call will run another iteration of the loop you have written in the function and 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 to an end, or because you no longer satisfy an `\"if/else\"`.\r\n\r\n---\r\n\r\nYour code explained\r\n-------------------\r\n\r\n*Generator:*\r\n\r\n # Here you create the method of the node object that will return the generator\r\n def _get_child_candidates(self, distance, min_dist, max_dist):\r\n\r\n # Here is the code that will be called each time you use the generator object:\r\n\r\n # If there is still a child of the node object on its left\r\n # AND if the distance is ok, return the next child\r\n if self._leftchild and distance - max_dist < self._median:\r\n yield self._leftchild\r\n\r\n # If there is still a child of the node object on its right\r\n # AND if the distance is ok, return the next child\r\n if self._rightchild and distance + max_dist >= self._median:\r\n yield self._rightchild\r\n\r\n # If the function arrives here, the generator will be considered empty\r\n # There are no more than two values: the left and the right children\r\n\r\n*Caller:*\r\n\r\n # Create an empty list and a list with the current object reference\r\n result, candidates = list(), [self]\r\n\r\n # Loop on candidates (they contain only one element at the beginning)\r\n while candidates:\r\n\r\n # Get the last candidate and remove it from the list\r\n node = candidates.pop()\r\n\r\n # Get the distance between obj and the candidate\r\n distance = node._get_dist(obj)\r\n\r\n # If the distance is ok, then you can fill in the result\r\n if distance <= max_dist and distance >= min_dist:\r\n result.extend(node._values)\r\n\r\n # Add the children of the candidate to the candidate's list\r\n # so the loop will keep running until it has looked\r\n # at all the children of the children of the children, etc. of the candidate\r\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\r\n\r\n return result\r\n\r\nThis code contains several smart parts:\r\n\r\n- The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, `candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))` exhausts 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.\r\n\r\n- The `extend()` method is a list object method that expects an iterable and adds its values to the list.\r\n\r\nUsually, we pass a list to it:\r\n\r\n >>> a = [1, 2]\r\n >>> b = [3, 4]\r\n >>> a.extend(b)\r\n >>> print(a)\r\n [1, 2, 3, 4]\r\n\r\nBut in your code, it gets a generator, which is good because:\r\n\r\n1. You don't need to read the values twice.\r\n2. You may have a lot of children and you don't want them all stored in memory.\r\n\r\nAnd it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...\r\n\r\nYou can stop here, or read a little bit to see an advanced use of a generator:\r\n\r\nControlling a generator exhaustion\r\n------\r\n\r\n >>> class Bank(): # Let's create a bank, building ATMs\r\n ... crisis = False\r\n ... def create_atm(self):\r\n ... while not self.crisis:\r\n ... yield \"$100\"\r\n >>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want\r\n >>> corner_street_atm = hsbc.create_atm()\r\n >>> print(corner_street_atm.next())\r\n $100\r\n >>> print(corner_street_atm.next())\r\n $100\r\n >>> print([corner_street_atm.next() for cash in range(5)])\r\n ['$100', '$100', '$100', '$100', '$100']\r\n >>> hsbc.crisis = True # Crisis is coming, no more money!\r\n >>> print(corner_street_atm.next())\r\n <type 'exceptions.StopIteration'>\r\n >>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs\r\n >>> print(wall_street_atm.next())\r\n <type 'exceptions.StopIteration'>\r\n >>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty\r\n >>> print(corner_street_atm.next())\r\n <type 'exceptions.StopIteration'>\r\n >>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business\r\n >>> for cash in brand_new_atm:\r\n ... print cash\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n $100\r\n ...\r\n\r\n**Note:** For Python 3, use`print(corner_street_atm.__next__())` or `print(next(corner_street_atm))`\r\n\r\nIt can be useful for various things like controlling access to a resource.\r\n\r\nItertools, your best friend\r\n-----\r\n\r\nThe `itertools` module contains special functions to manipulate iterables. Ever wish to duplicate a generator?\r\nChain two generators? Group values in a nested list with a one-liner? `Map / Zip` without creating another list?\r\n\r\nThen just `import itertools`.\r\n\r\nAn example? Let's see the possible orders of arrival for a four-horse race:\r\n\r\n >>> horses = [1, 2, 3, 4]\r\n >>> races = itertools.permutations(horses)\r\n >>> print(races)\r\n <itertools.permutations object at 0xb754f1dc>\r\n >>> print(list(itertools.permutations(horses)))\r\n [(1, 2, 3, 4),\r\n (1, 2, 4, 3),\r\n (1, 3, 2, 4),\r\n (1, 3, 4, 2),\r\n (1, 4, 2, 3),\r\n (1, 4, 3, 2),\r\n (2, 1, 3, 4),\r\n (2, 1, 4, 3),\r\n (2, 3, 1, 4),\r\n (2, 3, 4, 1),\r\n (2, 4, 1, 3),\r\n (2, 4, 3, 1),\r\n (3, 1, 2, 4),\r\n (3, 1, 4, 2),\r\n (3, 2, 1, 4),\r\n (3, 2, 4, 1),\r\n (3, 4, 1, 2),\r\n (3, 4, 2, 1),\r\n (4, 1, 2, 3),\r\n (4, 1, 3, 2),\r\n (4, 2, 1, 3),\r\n (4, 2, 3, 1),\r\n (4, 3, 1, 2),\r\n (4, 3, 2, 1)]\r\n\r\n\r\nUnderstanding the inner mechanisms of iteration\r\n------\r\n\r\nIteration is a process implying iterables (implementing the `__iter__()` method) and iterators (implementing the `__next__()` method).\r\nIterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.\r\n\r\nThere is more about it in this article about [how `for` loops work][1].\r\n\r\n [1]: https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm\r\n\r\n [`yield`]: https://docs.python.org/3/reference/simple_stmts.html#yield\r\n [generators]: https://docs.python.org/3/glossary.html#term-generator\r\n [iterables]: https://docs.python.org/3/glossary.html#term-iterable\r\n [iterators]: https://docs.python.org/3/glossary.html#term-iterator",
"comment_count": 13,
"content_license": "CC BY-SA 4.0",
"created_at_ms": 1224802124000,
"is_accepted": true,
"last_activity_at_ms": 1711253853000,
"last_edit_at_ms": 1711253853000,
"owner": {
"display_name": "Bite code",
"link": "https://stackoverflow.com/users/9951/bite-code",
"reputation": 601941,
"user_id": 9951,
"user_type": "registered"
},
"question_id": 231767,
"question_title": "What does the \"yield\" keyword do in Python?",
"score": 18317,
"site": "stackoverflow",
"source_url": "https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python/231855#231855"
},
"question": {
"accepted_answer_id": 231855,
"answer_count": 51,
"body_html": "<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>\n<p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p>\n<pre><code>def _get_child_candidates(self, distance, min_dist, max_dist):\n if self._leftchild and distance - max_dist < self._median:\n yield self._leftchild\n if self._rightchild and distance + max_dist >= self._median:\n yield self._rightchild \n</code></pre>\n<p>And this is the caller:</p>\n<pre><code>result, candidates = [], [self]\nwhile candidates:\n node = candidates.pop()\n distance = node._get_dist(obj)\n if distance <= max_dist and distance >= min_dist:\n result.extend(node._values)\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\nreturn result\n</code></pre>\n<p>What happens when the method <code>_get_child_candidates</code> is called?\nIs a list returned? A single element? Is it called again? When will subsequent calls stop?</p>\n\n<hr />\n<sub>\n1. 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> \n",
"body_markdown": "What functionality does the [`yield`] keyword in Python provide?\r\n\r\nFor example, I'm trying to understand this code<sup>**1**</sup>:\r\n\r\n def _get_child_candidates(self, distance, min_dist, max_dist):\r\n if self._leftchild and distance - max_dist < self._median:\r\n yield self._leftchild\r\n if self._rightchild and distance + max_dist >= self._median:\r\n yield self._rightchild\t\r\n\r\nAnd this is the caller:\r\n\r\n result, candidates = [], [self]\r\n while candidates:\r\n node = candidates.pop()\r\n distance = node._get_dist(obj)\r\n if distance <= max_dist and distance >= min_dist:\r\n result.extend(node._values)\r\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\r\n return result\r\n\r\nWhat happens when the method `_get_child_candidates` is called?\r\nIs a list returned? A single element? Is it called again? When will subsequent calls stop?\r\n\r\n\r\n[`yield`]: https://docs.python.org/3/reference/simple_stmts.html#yield\r\n\r\n<!-- https://docs.python.org/3/reference/expressions.html#yieldexpr -->\r\n\r\n\r\n----------\r\n\r\n\r\n<sub>\r\n1. 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/\">Module mspace</a>.</sub> ",
"closed_at_ms": null,
"closed_reason": null,
"comment_count": 6,
"content_license": null,
"created_at_ms": 1224800471000,
"is_answered": true,
"last_activity_at_ms": 1777574627000,
"last_edit_at_ms": 1711253482000,
"owner": {
"display_name": "Alex. S.",
"link": "https://stackoverflow.com/users/18300/alex-s",
"reputation": 148444,
"user_id": 18300,
"user_type": "registered"
},
"question_id": 231767,
"score": 13135,
"site": "stackoverflow",
"source_url": "https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python",
"tags": [
"python",
"iterator",
"generator",
"yield"
],
"title": "What does the \"yield\" keyword do in Python?",
"view_count": 3499052
}
}
],
"site": "stackoverflow",
"source_url": "https://api.stackexchange.com/2.3/search/advanced?site=stackoverflow&tagged=python&accepted=true&pagesize=1&sort=votes&filter=%217ry9ouLWcQWrdWSzrv7eT0TX0kxJ.zt0R1",
"tagged": [
"python"
],
"total": 1144387
}Request contract
- Method and path: POST /apis/v1/stackexchange-com/questions/accepted-answers
- Availability: enabled
- Request URL template:
https://api.aisa.one/apis/v1/stackexchange-com/questions/accepted-answers
{
"operationId": "stackexchange-com.questions.accepted-answers",
"method": "POST",
"path": "/apis/v1/stackexchange-com/questions/accepted-answers",
"servers": [
{
"url": "https://api.aisa.one"
}
],
"parameters": [],
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"content": {
"application/json": {
"examples": {
"provider": {
"summary": "Official provider example; checked against AIsa request constraints",
"value": {
"pagesize": 1,
"sort": "votes",
"tagged": [
"python"
]
}
}
},
"schema": {
"additionalProperties": true,
"properties": {
"include_body": {
"description": "include_body",
"type": "boolean",
"x-alexandria-option-metadata": {
"in": "body"
}
},
"key": {
"description": "Optional Stack Exchange application key. Raises the per-IP quota from 300 to 10,000 requests per day and unlocks pages above 25, which the API refuses anonymously. Keys are public identifiers, not secrets.",
"type": "string",
"x-alexandria-option-metadata": {
"in": "body"
}
},
"page": {
"default": 1,
"description": "Pages above 25 need `key`: Stack Exchange serves deeper pages only with an application key (`access_denied` otherwise). Without one the last page reports partial coverage.\n\nProvider reference: minimum 1; maximum 10000; default 1.",
"type": "number",
"x-alexandria-option-metadata": {
"in": "body",
"max": 10000,
"min": 1
}
},
"pagesize": {
"default": 10,
"description": "pagesize\n\nProvider reference: minimum 1; maximum 30; default 10.",
"type": "number",
"x-alexandria-option-metadata": {
"in": "body",
"max": 30,
"min": 1
}
},
"q": {
"description": "q",
"type": "string",
"x-alexandria-option-metadata": {
"in": "body"
}
},
"site": {
"default": "stackoverflow",
"description": "Stack Exchange site API parameter, e.g. stackoverflow, superuser, math, askubuntu, english, physics. Use `sites` to list them. Pattern: ^[a-z0-9]+(\\.[a-z0-9]+)*$.\n\nProvider reference: default \"stackoverflow\".",
"type": "string",
"x-alexandria-option-metadata": {
"in": "body"
}
},
"sort": {
"default": "votes",
"description": "sort\n\nProvider reference: allowed values [\"votes\", \"activity\", \"creation\", \"relevance\"]; default \"votes\".",
"type": "string",
"x-alexandria-option-metadata": {
"in": "body",
"oneOf": [
"votes",
"activity",
"creation",
"relevance"
]
}
},
"tagged": {
"description": "tagged",
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"tagged"
],
"type": "object"
}
}
},
"required": true
},
"x-aisa-status": "enabled",
"components": {
"securitySchemes": {
"bearerAuth": {
"scheme": "bearer",
"type": "http"
}
}
}
}
Cost and request rules
Usage-based pricing. Default request estimate: $0.0005 USD. The final charge depends on actual usage. Your account price may differ; use a request quote where supported.Authorizations
Body
application/json
Response
Accepted answers by topic: the top questions on one site carrying every tag in tagged (optionally narrowed by q), each paired with its accepted answer. One search call plus one batched answers call; has_more + page paginate.
The response contains the tool result directly.
| Documented field | Provider type | Description |
|---|---|---|
count | number | |
has_more | boolean | |
observed_at_ms | number | |
page | number | |
q | string | |
quota | object | |
results | object[] | |
site | string | |
source_url | string | |
tagged | string[] | |
total | number | Total questions with an accepted answer matching the filter. |
These are the provider's documented fields. Field requiredness, nullability and nested object structures are specified only where the descriptions explicitly say so.