Can we keep Python modules in compiled format?

PythonServer Side ProgrammingProgramming

Yes you can keep Python modules in compiled format. Python automatically compiles Python source code when you import a module, so the easiest way to create a PYC file is to import it. If you have a module, just do:

>>> import mymodule

to create a mymodule.pyc file in the same directory. A drawback is that it doesn’t only compile the module, it also executes it, which may not be what you want. (however, it does compile the entire script even if it fails to execute the script). To do this programmatically, and without executing the code, you can use the 'py_compile' module:

>>> import py_compile
>>> py_compile.compile("")

There’s also a 'compileall' module which can be used to compile all modules in an entire directory tree.

>>> import compileall
>>> compileall.compile_dir("mylib", force=1)

Note that Python’s byte code is portable between platforms, but not necessarily between Python releases.

Updated on 01-Oct-2019 10:44:19