Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Python Virtual Machine (CPython) convert bytecode into machine language?

Tags:

python

I'm a little confused as to how the PVM gets the cpu to carry out the bytecode instructions. I had read somewhere on StackOverflow that it doesn't convert byte-code to machine code, (alas, I can't find the thread now).

Does it already have tons of pre-compiled machine instructions hard-coded that it runs/chooses one of those depending on the byte code?

Thank you.

like image 372
Moondra Avatar asked Jul 28 '17 18:07

Moondra


People also ask

Does bytecode get converted to machine code?

An example of bytecode The CLASS file is then read and processed by a Java virtual machine (JVM) running on a target system. The JVM, which is part of the Java Runtime Environment, interprets the bytecode and converts it to machine language specific to the intended platform.

How does CPython VM work?

CPython's VM is stack-based. It means that it executes instructions using the stack to store and retrieve data. The LOAD_FAST instruction pushes a local variable onto the stack. LOAD_CONST pushes a constant.

Is Python converted to bytecode?

Instead of translating source code to machine code like C++, Python code it translated to bytecode. This bytecode is a low-level set of instructions that can be executed by an interpreter.

What converts Python to bytecode?

The default implementation of the Python programming language is CPython which is written in the C programming language. CPython compiles the python source code into the bytecode, and this bytecode is then executed by the CPython virtual machine.


1 Answers

It's a lot higher-level than machine language. There's a giant switch statement that looks at each opcode and decides what to do based on the opcode. Here are some snippets:

switch (opcode) {
...
TARGET(LOAD_CONST) {
    PyObject *value = GETITEM(consts, oparg);
    Py_INCREF(value);
    PUSH(value);
    FAST_DISPATCH();
}
...
TARGET(UNARY_NEGATIVE) {
    PyObject *value = TOP();
    PyObject *res = PyNumber_Negative(value);
    Py_DECREF(value);
    SET_TOP(res);
    if (res == NULL)
        goto error;
    DISPATCH();
}
...
TARGET(BINARY_MULTIPLY) {
    PyObject *right = POP();
    PyObject *left = TOP();
    PyObject *res = PyNumber_Multiply(left, right);
    Py_DECREF(left);
    Py_DECREF(right);
    SET_TOP(res);
    if (res == NULL)
        goto error;
    DISPATCH();
}

The TARGET and DISPATCH stuff is part of an optimization that doesn't quite go through the regular switch mechanics. Functions like PyNumber_Negative and PyNumber_Multiply are part of the Python C API, and they dispatch operations like negation and multiplication.

like image 159
user2357112 supports Monica Avatar answered Oct 12 '22 22:10

user2357112 supports Monica