Why compile Python code?

ryeguy picture ryeguy · Jan 22, 2009 · Viewed 197.2k times · Source

Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?

I also notice that some files in my application get compiled into .pyc while others do not, why is this?

Answer

Georg Schölly picture Georg Schölly · Jan 23, 2009

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.