Skip to content

Python Interpreter

Interpreter = executes code as instructions step by step

  • runs in an env (process VM) that usually software simulator for machine to code run portably (the interpreter can take bytecode and map to pre-compiled C code for current machine) Compiler = instructions are bundled into machine-ready package (executable).
  • runs directly on cpu

CPython is a machine native (OSX, Linux, WIndows, ARM, x86, etc) compiled application that is a runtime interpreter for Python

  • it will compile the code into bytecode
  • then use Python VM (process VM) to execute the bytecode
    • by reading bytecode instructions and dispatching to C code
    • Containers VMs Hypervisor
    • VM - software to simulate machine
    • uses OS syscalls
YoYour .py source
      ->
  Python bytecode
      ->
  Python VM / bytecode evaluator
      ->
  CPython interpreter process
      ->
  Host OS (syscalls)
      ->
  Hardware (CPU)

Interpreter under the hood

  • it maps the bytecode operations to native C functions
  • and all those C functions (C Code) is already compiled into ARM or x86 machine code

  1. .py source
     "x = 2 + 3; print(x)"

  2. Python bytecode
     LOAD_CONST 5
     STORE_NAME x
     LOAD_NAME print
     LOAD_NAME x
     CALL 1

  3. CPython bytecode evaluator
     reads LOAD_CONST 5
     pushes Python int object 5 onto stack
       while (running) {
      instruction = next_bytecode();

      switch (instruction.opcode) {
          case LOAD_NAME:
              // C code to load a Python variable
              break;

          case BINARY_OP:
              // C code to perform Python addition
              break;

          case STORE_NAME:
              // C code to store a Python variable
              break;
	      }
	  }

  4. Precompiled CPython machine code
     CPU runs CPython's compiled code for:
     "push constant", "store variable", "call function"
     
     (precompiled c code at the time of Python install)

  5. OS syscall
     print(x) eventually asks OS:
     write stdout bytes: "5\n"

  6. Hardware
     CPU executes machine instructions
     terminal/display shows:
     5

Why interpreter?

to compile for different machines, requires different compilation methods

interpreter can allow for intermediate portable instruction set to be consumed and installed interpreter can run it natively on the machine. so now the compile to intermediate bytecode is the same across all machines, and each machine type can have it's own interpreter downloaded to execute the bytecode accordingly