CPython

so following my new curiosity over all things internals, its been a pleasure so far reading about CPython, especially because i remember loving the Languages and Complilers module we had in Hull Uni. Feels like a lifetime ago, but i remember it was very instinctive to me how a compiler worked and the baby one we built as a coursework came naturally. Oh beloved Yacc and Bison.

Unfortunately, i did not come accross anything to do with compliers in my studies… i guess up until now. this book details how python works under the hood and im excited to get to the compiler bits!

so far, the most interesting thing i have read is even though we all know python is an interpreted language, its interesting to know that its actually first compiled before its interpreted. I mean we have all see the .pyc file in our directories after running a python file. turns out, thats the file that is interpreted. not the code written in python.

What happens when you run Python Code

Heres the flow:

  • You download python
  • But you are actually downloading 3 things
    • the cpython compiler
    • the cpython virtual machine (just a C program)
    • the python library
  • You write python code
  • you run python3 my_python_file.py on your command line
  • the cpython compiler compiles your python code to bytecode
  • and saves the bytecode to a file called my_python_file.pyc
  • the cpython virtual machine then interprets the my_python_file.pyc file line by line

the bytecode interpreter is a loop that goes round and iterates over the file until there are no more commands to execute.

pretty neat!