Is it possible to import a compiled python file? Is it possible to import a compiled python file? python python

Is it possible to import a compiled python file?


If there is foo.pyc, import foo will automatically use foo.pyc whether foo.py exists or not

(If foo.py is newer, it will be used)

http://docs.python.org/tutorial/modules.html


Use the import without the extension. Python will than look if the file has changed, if not it will use the previously created pyc file.

But note that if you really want more performance, I recommend you to use PyPy which is a lot faster than the standard CPython implementation. (But note that it is still Python 2)


In a nutshell, to import a Python compiled file (e.g. module.pyc) only, simply place it in the same directory where the source (e.g module.py) would be, and ensure that there is no corresponding source file (module.py in our example) there. Then the usual import module will work seamlessly.

If there is a source file in the same directory as the compiled file, Python will use the compiled file in the __pycache__ directory instead, or recompile from source if it's not there.

If you remove the source file without putting a ".pyc" in the same directory, the import will fail even if the compiled file exists in the __pycache__ directory. Also note that files under __pycache__ follow a different naming convention. If you copy them across, make sure that they are renamed so that it has the same name as the source file, except that the extension must be "pyc" rather than "py".

There is a very nice flow chart in PEP 3147 linked from the documentation.