What method does the Python interpreter use to compute a jump target in bytecode?
<p>It is my understanding, that after the Python interpreter has created an Abstract Syntax Tree, it then begins to generate byte-code from that Abstract Syntax Tree, which will later be executed by the Python Virtual Machine. Most Python programs of course, cannot just be sequentially executed, and make use of control flow. Which mean that the Interpreter must also generate jump targets.</p>

<p>For instance, when the Python interpreter comes to an if statement in the abstract syntax tree, it must compute the correct jump target that will be used by the Virtual Machine depending on the if statement condition. I cannot however, figure out what method the Python interpreter use to compute the correct jump target in its bytecode.</p>

<p>While currently in the process of creating a simple scripting language that would be Executed by a Virtual Machine, I could not figure out how I would compute the correct jump targets for the VM.</p>

<p>The method I used at first was:</p>

<ul>
<li>Calculate the current length of the list of Virtual Machine instructions</li>
<li>Temporarily generate the instructions for the if statements block</li>
<li>Calculate the new length of the list of Virtual Machine instructions</li>
<li>After Temporarily generating the instructions for the if statements block to find how much space it would require to jump the block, Reset the instructions list to its original length by using the length of the instructions before temporarily generating the instructions.</li>
</ul>

<p>Or in pseudo code:</p>

<pre><code>def walk()
    while true:
         instructions_list.add(walk(instructions))
         ...
         if current_node == if_statement:
             current_length = instructions_list.length()
             for each statement in the if block:
                 walk(statement)
             new_length = instructions_list.length()
             jump_target = new_length
</code></pre>

<p>This however seems inefficient and clunky, and I'm almost sure that the Python Interpreter does not use this method. That being said, <strong>what method exactly does the Python Interpreter use to calculate its jump targets</strong>?</p>