[Python] What is the length of a python bytecode instruction in CPython?

Discussão em 'Python' iniciado por Stack, Agosto 7, 2025.

  1. Stack

    Stack Membro Participativo

    Python docs on the dis module state that the length of a python bytecode instruction in CPython is 2 bytes (https://docs.python.org/3/library/dis.html)

    However, when I disassemble a function and look at the actual bytecode, I see that the instructions only take up 1 byte:

    def example_function(x):
    if x > 0:
    return x + 1
    return 0


    print(example_function.__code__.co_code.hex())

    97007c0064016b44000072057c0064027a00000053007901


    dis.dis(example_function)

    10 0 RESUME 0

    11 2 LOAD_FAST 0 (x)
    4 LOAD_CONST 1 (0)
    6 COMPARE_OP 68 (>)
    10 POP_JUMP_IF_FALSE 5 (to 22)

    12 12 LOAD_FAST 0 (x)
    14 LOAD_CONST 2 (1)
    16 BINARY_OP 0 (+)
    20 RETURN_VALUE

    13 >> 22 RETURN_CONST 1 (0)



    Are they variable in length?

    The instruction list defined in dis.opname does have a few instructions longer than 1 byte, but how does then the interpreter know when it's 1 byte and when it's 2 bytes?

    As you can see above, I've tried disassembling the code to see for myself and inspected the docs.

    Continue reading...

Compartilhe esta Página