Moondra
Moondra

Reputation: 4521

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

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.

Upvotes: 8

Views: 3208

Answers (2)

Kamyar
Kamyar

Reputation: 2694

If you mean Standard Python (CPython) by Python, then no! The byte-code (.pyc or .pyo files) are just a binary version of your code line by line, and is interpreted at run-time. But if you use pypy, yes! It has a JIT Compiler and it runs your byte-codeas like Java dn .NET (CLR).

Upvotes: 3

user2357112
user2357112

Reputation: 281330

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.

Upvotes: 7

Related Questions