0

I know that Pyhon compiles source code to a Byte Code before the interpreter works on it. What does this Byte Code look/behave like?

2
Contributors
1
Reply
2
Views
11 Years
Discussion Span
Last Post by vegaseat
0

Python Byte Code is actually machine code. To be specific, it is machine code for the Python Virtual Machine within the interpreter. Java does something quite similar for the Java Virtual Machine (JVM). Since the machine code is not written for a specific CPU Python like Java becomes much more cross-platform. The compiled byte code files (.pyc or .pyo) can run on many different machines. It's the interpreter that is machine specific.

Python itself does not have an assembler, but you can disassemble Byte Code and it looks a lot like Assembly Language. Here is an example ...

# the Python Virtual Machine Instructions (byte code)
# can be disassembled and mimic assembly code
# for instance:
# LOAD_FAST  var_num  --> pushes a reference to local co_varnames[var_num] onto the stack
# STORE_FAST  var_num --> stores top of stack into the local co_varnames[var_num]
# LOAD_CONST  consti  --> pushes co_consts[consti] onto the stack


import dis

def myfunc():
    a = 2
    b = 3
    print "adding a and b and 3"
    c = a + b + 3
    if c > 7:
        return c
    else:
        return None

# this disassembles the above function's code
dis.dis(myfunc)

"""
  7           0 LOAD_CONST               1 (2)
              3 STORE_FAST               0 (a)

  8           6 LOAD_CONST               2 (3)
              9 STORE_FAST               2 (b)

  9          12 LOAD_CONST               3 ('adding a and b and 3')
             15 PRINT_ITEM
             16 PRINT_NEWLINE

 10          17 LOAD_FAST                0 (a)
             20 LOAD_FAST                2 (b)
             23 BINARY_ADD
             24 LOAD_CONST               2 (3)
             27 BINARY_ADD
             28 STORE_FAST               1 (c)

 11          31 LOAD_FAST                1 (c)
             34 LOAD_CONST               4 (7)
             37 COMPARE_OP               4 (>)
             40 JUMP_IF_FALSE            8 (to 51)
             43 POP_TOP

 12          44 LOAD_FAST                1 (c)
             47 RETURN_VALUE
             48 JUMP_FORWARD             5 (to 56)
        >>   51 POP_TOP

 14          52 LOAD_CONST               0 (None)
             55 RETURN_VALUE
        >>   56 LOAD_CONST               0 (None)
             59 RETURN_VALUE

"""

Talking about Java, there is actually a modified Python called Jython that produces Java Byte Code for the JVM and can use the Java libraries.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.