pythonpyc

When do Python cached bytecode (pyc) files get updated?


Sometimes I am running unittest on a specific module by pointing to make PYTHON_TEST=path_of_module_to_test test and if this module path_of_module_to_test test imports some other python module that was updated, will importing done from this module be taken from the updated py source file or from the unupdated pyc file, or will the import lead to updating of the dependent pyc file?


Solution

  • From PEP 3147:

    CPython compiles its source code into "byte code", and for performance reasons, it caches this byte code on the file system whenever the source file has changes. This makes loading of Python modules much faster because the compilation phase can be bypassed. When your source file is foo.py , CPython caches the byte code in a foo.pyc file right next to the source.

    If your source changes; CPython will recompile and re-cached the bytecode.

    Note that the above is for Python 2.x. This all changed in Python 3.x in Python 3.2: PEP 3147: PYC Repository Directories

    Note: When we refer to "CPython" here we are referring to the implementation of Python that you are most likely using from https://www.python.org as this behaviour (I believe) is implementation specific.