Main Content

Python - how it saves on compile time

Archive - Originally posted on "The Horse's Mouth" - 2009-10-20 04:21:20 - Graham Ellis

Python is interpreted every time you run the code ... or that's the simple first story you're told. But really it's not that simple ... and not that inefficient.

When you run a Python program, it is not interpreted line by line as you run it - it is interpreted all at once before it's run at all, and stored as "byte code" so that loops and methods don't need to be re-interpreted hundreds or thousands of times during a single execution ... the Python virtual machine (for that's what it is) simply comes back to the already-worked-out store.

It gets even more efficient when you come to modules that you load through from or import. Their virtual machine code is saves into files with the extension .pyc (or .pyo if you use the optimize option) and they are loaded directly without the need to recompile on future runs. A quick operating system check on file time stamps means that if you change your source file, it will be 'silently' recompiled and resaved.

Other languages which are described as 'scripting' languages use a similar technique. See here, for example, to see how Lua does it.