Python execution from bytecode

Viewed 42

Let's take the following python function:

def add(x,y):
    return x+y

Disassembling it gives me:

dis.dis(add)
2           0 LOAD_FAST                0 (x)
            2 LOAD_FAST                1 (y)
            4 BINARY_ADD
            6 RETURN_VALUE

This seems pretty similar to the (non-optimized) assembly instructions that would be run on an addition, something along the lines of:

mov %rdi, %rax   # LOAD_FAST x
mov %rsi, %rbx   # LOAD_FAST y
add %rbx, %rax   # BINARY_ADD
mov %rax, %rax   # RETURN_VALUE, just including here to be explicit

My question is what does pythondo once it has the byte code. Does it run it on the machine or are there various C function that it calls to do each of the instructions? For example, the above would be translated into:

{
    ...
    int(?) x = 0;
    int(?) y = 1;
    int(?) tmp = y+x;
    return tmp;
}

What would be a good resource to learn this (for example, the C file(s) where the actual evaluation/execution is done)?


There is an interesting answer here about how it is done in CPython: https://stackoverflow.com/a/19917906/651174. Do all implementations do this somewhat similarly, or does this vary? How much does the python standard require (or not at all)?

0 Answers
Related