> ## Documentation Index
> Fetch the complete documentation index at: https://aisa.one/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> - Base URLs: models `https://api.aisa.one/v1` (Gemini GenerateContent: `https://api.aisa.one/v1beta`); data APIs `https://api.aisa.one/apis/v1`. The `servers` of each operation in https://aisa.one/openapi.yaml is authoritative.
> - Auth: `Authorization: Bearer $AISA_API_KEY`. Never print, log, or commit the key.
> - MCP (preferred for agents): `https://mcp.aisa.one/mcp`, signed in with OAuth, so there is no key to paste.
> - Agent Skill: `npx skills add AIsa-team/agent-skills --skill aisa`. Fallback with the AIsa CLI: `aisa skills install aisa`.
> - Spending: docs, https://aisa.one/models, https://aisa.one/api, `/v1/models`, and MCP `search`, `list_categories`, `get_details`, `batch_quote`, and the `account` operation are free. Quote the exact calls before running them (MCP `batch_quote`, CLI `aisa quote --json`). If the quote reports `auto_execute_eligible: true`, run it unless the user set a tighter limit or asked only for a quote. Otherwise, tell the user in one message the planned calls, the quoted price, and a total USD budget for the task, then wait for approval. Direct HTTP calls follow the stricter rule at https://aisa.one/docs/get-started/cli.md#direct-http-fallback. Do not make paid calls to test availability. Full rule: https://aisa.one/llms.txt

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

## 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`

[Complete OpenAPI definition](https://aisa.one/docs/openapi/stackexchange-com.json)

Effective request declaration (including authentication and referenced schemas):

```json theme={null}
{
  "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.


## OpenAPI

````yaml openapi/stackexchange-com.json POST /apis/v1/stackexchange-com/questions/accepted-answers
openapi: 3.1.0
info:
  description: ''
  title: Stack Exchange
  version: '1'
  x-aisa-capabilities:
    idempotency: Idempotency-Key
    max_price: X-AISA-Max-Price-USD
    quote:
      header: X-AISA-Cost-Mode
      value: quote
  x-aisa-catalogs:
    stackexchange-com:
      description: ''
      title: Stack Exchange
      x-aisa-capabilities:
        idempotency: Idempotency-Key
        max_price: X-AISA-Max-Price-USD
        quote:
          header: X-AISA-Cost-Mode
          value: quote
      x-aisa-document:
        facts_hash: 5bc97b6e49cd2980b95f225d7763c2c1917cc4efdfd41fb9e7e3dfd2260a12e8
        generator_version: '3'
        protocol_version: '1'
        schema_version: '1'
      x-aisa-plans:
        builder: 1
        display_plan: payg
        payg: 1
        similarweb_payg: 1
        team: 1
        version: e70a0959cd1b93b84ae16dffd7a538273ddb9c1d46277b82823c37ff1b6bc0fb
  x-aisa-configured-paths:
    - /apis/v1/stackexchange-com/questions/accepted-answers
    - /apis/v1/stackexchange-com/questions/answer
    - /apis/v1/stackexchange-com/questions/answers
    - /apis/v1/stackexchange-com/questions/question
    - /apis/v1/stackexchange-com/questions/revisions
    - /apis/v1/stackexchange-com/questions/search
    - /apis/v1/stackexchange-com/questions/sites
  x-aisa-document:
    composer_version: '31'
    document_hash: sha256:5f7ff3362d41bef80c277294811263969f47b5bd6b614be4b40139c0088eeef2
    facts_hash: 5bc97b6e49cd2980b95f225d7763c2c1917cc4efdfd41fb9e7e3dfd2260a12e8
    generator_version: '3'
    protocol_version: '1'
    response_pending: []
    schema_version: '1'
  x-aisa-plans:
    builder: 1
    display_plan: payg
    payg: 1
    similarweb_payg: 1
    team: 1
    version: e70a0959cd1b93b84ae16dffd7a538273ddb9c1d46277b82823c37ff1b6bc0fb
  x-aisa-provider: stackexchange-com
servers:
  - url: https://api.aisa.one
security:
  - bearerAuth: []
paths:
  /apis/v1/stackexchange-com/questions/accepted-answers:
    post:
      tags:
        - Stack Exchange
      summary: Accepted answers
      description: >-
        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.
      operationId: stackexchange-com.questions.accepted-answers
      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.


                    Provider reference: minimum 1; maximum 10000; default 1.
                  type: number
                  x-alexandria-option-metadata:
                    in: body
                    max: 10000
                    min: 1
                pagesize:
                  default: 10
                  description: |-
                    pagesize

                    Provider 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]+)*$.


                    Provider reference: default "stackoverflow".
                  type: string
                  x-alexandria-option-metadata:
                    in: body
                sort:
                  default: votes
                  description: >-
                    sort


                    Provider 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
      responses:
        '200':
          content:
            application/json:
              examples:
                provider:
                  description: >-
                    Published by the provider on
                    2026-09-15T05:04:10.776785+00:00.
                  summary: Official provider example
                  value:
                    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>

                            <h2>Iterables</h2>

                            <p>When you create a list, you can read its items
                            one by one. Reading its items one by one is called
                            iteration:</p>

                            <pre><code>&gt;&gt;&gt; mylist = [1, 2, 3]

                            &gt;&gt;&gt; for i in mylist:

                            ...    print(i)

                            1

                            2

                            3

                            </code></pre>

                            <p><code>mylist</code> is an <em>iterable</em>. When
                            you use a list comprehension, you create a list, and
                            so an iterable:</p>

                            <pre><code>&gt;&gt;&gt; mylist = [x*x for x in
                            range(3)]

                            &gt;&gt;&gt; for i in mylist:

                            ...    print(i)

                            0

                            1

                            4

                            </code></pre>

                            <p>Everything you can use &quot;<code>for...
                            in...</code>&quot; on is an iterable;
                            <code>lists</code>, <code>strings</code>,
                            files...</p>

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

                            <h2>Generators</h2>

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

                            <pre><code>&gt;&gt;&gt; mygenerator = (x*x for x in
                            range(3))

                            &gt;&gt;&gt; for i in mygenerator:

                            ...    print(i)

                            0

                            1

                            4

                            </code></pre>

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

                            <h2>Yield</h2>

                            <p><code>yield</code> is a keyword that is used like
                            <code>return</code>, except the function will return
                            a generator.</p>

                            <pre><code>&gt;&gt;&gt; def create_generator():

                            ...    mylist = range(3)

                            ...    for i in mylist:

                            ...        yield i*i

                            ...

                            &gt;&gt;&gt; mygenerator = create_generator() #
                            create a generator

                            &gt;&gt;&gt; print(mygenerator) # mygenerator is an
                            object!

                            &lt;generator object create_generator at
                            0xb7555c34&gt;

                            &gt;&gt;&gt; for i in mygenerator:

                            ...     print(i)

                            0

                            1

                            4

                            </code></pre>

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

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

                            <p>Then, your code will continue from where it left
                            off each time <code>for</code> uses the
                            generator.</p>

                            <p>Now the hard part:</p>

                            <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>&quot;if/else&quot;</code>.</p>

                            <hr />

                            <h2>Your code explained</h2>

                            <p><em>Generator:</em></p>

                            <pre><code># Here you create the method of the node
                            object that will return the generator

                            def _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 and distance - max_dist &lt; self._median:
                                    yield self._leftchild

                                # If there is still a child of the node object on its right
                                # AND if the distance is ok, return the next child
                                if self._rightchild and distance + max_dist &gt;= self._median:
                                    yield self._rightchild

                                # If the function arrives here, the generator will be considered empty
                                # There are no more than two values: the left and the right children
                            </code></pre>

                            <p><em>Caller:</em></p>

                            <pre><code># Create an empty list and a list with
                            the current object reference

                            result, candidates = list(), [self]


                            # Loop on candidates (they contain only one element
                            at the beginning)

                            while candidates:

                                # Get the last candidate and remove it from the list
                                node = candidates.pop()

                                # Get the distance between obj and the candidate
                                distance = node._get_dist(obj)

                                # If the distance is ok, then you can fill in the result
                                if distance &lt;= max_dist and distance &gt;= min_dist:
                                    result.extend(node._values)

                                # Add the children of the candidate to the candidate's list
                                # so the loop will keep running until it has 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 result

                            </code></pre>

                            <p>This code contains several smart parts:</p>

                            <ul>

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

                            </li>

                            <li><p>The <code>extend()</code> method is a list
                            object method that expects an iterable and adds its
                            values to the list.</p>

                            </li>

                            </ul>

                            <p>Usually, we pass a list to it:</p>

                            <pre><code>&gt;&gt;&gt; a = [1, 2]

                            &gt;&gt;&gt; b = [3, 4]

                            &gt;&gt;&gt; a.extend(b)

                            &gt;&gt;&gt; print(a)

                            [1, 2, 3, 4]

                            </code></pre>

                            <p>But in your code, it gets a generator, which is
                            good because:</p>

                            <ol>

                            <li>You don't need to read the values twice.</li>

                            <li>You may have a lot of children and you don't
                            want them all stored in memory.</li>

                            </ol>

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

                            <p>You can stop here, or read a little bit to see an
                            advanced use of a generator:</p>

                            <h2>Controlling a generator exhaustion</h2>

                            <pre><code>&gt;&gt;&gt; class Bank(): # Let's create
                            a bank, building ATMs

                            ...    crisis = False

                            ...    def create_atm(self):

                            ...        while not self.crisis:

                            ...            yield &quot;$100&quot;

                            &gt;&gt;&gt; hsbc = Bank() # When everything's ok
                            the ATM gives you as much as you want

                            &gt;&gt;&gt; corner_street_atm = hsbc.create_atm()

                            &gt;&gt;&gt; print(corner_street_atm.next())

                            $100

                            &gt;&gt;&gt; print(corner_street_atm.next())

                            $100

                            &gt;&gt;&gt; print([corner_street_atm.next() for
                            cash in range(5)])

                            ['$100', '$100', '$100', '$100', '$100']

                            &gt;&gt;&gt; hsbc.crisis = True # Crisis is coming,
                            no more money!

                            &gt;&gt;&gt; print(corner_street_atm.next())

                            &lt;type 'exceptions.StopIteration'&gt;

                            &gt;&gt;&gt; wall_street_atm = hsbc.create_atm() #
                            It's even true for new ATMs

                            &gt;&gt;&gt; print(wall_street_atm.next())

                            &lt;type 'exceptions.StopIteration'&gt;

                            &gt;&gt;&gt; hsbc.crisis = False # The trouble is,
                            even post-crisis the ATM remains empty

                            &gt;&gt;&gt; print(corner_street_atm.next())

                            &lt;type 'exceptions.StopIteration'&gt;

                            &gt;&gt;&gt; brand_new_atm = hsbc.create_atm() #
                            Build a new one to get back in business

                            &gt;&gt;&gt; for cash in brand_new_atm:

                            ...    print cash

                            $100

                            $100

                            $100

                            $100

                            $100

                            $100

                            $100

                            $100

                            $100

                            ...

                            </code></pre>

                            <p><strong>Note:</strong> For Python 3,
                            use<code>print(corner_street_atm.__next__())</code>
                            or <code>print(next(corner_street_atm))</code></p>

                            <p>It can be useful for various things like
                            controlling access to a resource.</p>

                            <h2>Itertools, your best friend</h2>

                            <p>The <code>itertools</code> module contains
                            special functions to manipulate iterables. Ever wish
                            to duplicate a generator?

                            Chain two generators? Group values in a nested list
                            with a one-liner? <code>Map / Zip</code> without
                            creating another list?</p>

                            <p>Then just <code>import itertools</code>.</p>

                            <p>An example? Let's see the possible orders of
                            arrival for a four-horse race:</p>

                            <pre><code>&gt;&gt;&gt; horses = [1, 2, 3, 4]

                            &gt;&gt;&gt; races = itertools.permutations(horses)

                            &gt;&gt;&gt; print(races)

                            &lt;itertools.permutations object at 0xb754f1dc&gt;

                            &gt;&gt;&gt;
                            print(list(itertools.permutations(horses)))

                            [(1, 2, 3, 4),
                             (1, 2, 4, 3),
                             (1, 3, 2, 4),
                             (1, 3, 4, 2),
                             (1, 4, 2, 3),
                             (1, 4, 3, 2),
                             (2, 1, 3, 4),
                             (2, 1, 4, 3),
                             (2, 3, 1, 4),
                             (2, 3, 4, 1),
                             (2, 4, 1, 3),
                             (2, 4, 3, 1),
                             (3, 1, 2, 4),
                             (3, 1, 4, 2),
                             (3, 2, 1, 4),
                             (3, 2, 4, 1),
                             (3, 4, 1, 2),
                             (3, 4, 2, 1),
                             (4, 1, 2, 3),
                             (4, 1, 3, 2),
                             (4, 2, 1, 3),
                             (4, 2, 3, 1),
                             (4, 3, 1, 2),
                             (4, 3, 2, 1)]
                            </code></pre>

                            <h2>Understanding the inner mechanisms of
                            iteration</h2>

                            <p>Iteration is a process implying iterables
                            (implementing the <code>__iter__()</code> method)
                            and iterators (implementing the
                            <code>__next__()</code> method).

                            Iterables are any objects you can get an iterator
                            from. Iterators are objects that let you iterate on
                            iterables.</p>

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

                            <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 &lt; self._median:
                                    yield self._leftchild
                                if self._rightchild and distance + max_dist &gt;= 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 &lt;= max_dist and distance &gt;= 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> 
                          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
              schema:
                not:
                  type: 'null'
                x-aisa-schema-completeness: documented-fields-only
          description: >-
            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.
        default:
          content:
            application/json:
              schema: {}
          description: >-
            Error response; upstream passthrough responses may use provider
            formats
components:
  securitySchemes:
    bearerAuth:
      scheme: bearer
      type: http

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.