File extension

.pyc

Python compiled bytecode

.pyc files are compiled Python bytecode files that the Python interpreter caches so modules do not have to be recompiled on every import.

Known meanings

Formats and reference material for .pyc

Python compiled bytecode

Cached bytecode for a Python module, generated by the interpreter

  • binaries
  • Python Software Foundation

Details

Format notes

PYC (Compiled Python Bytecode)

A .pyc file contains the compiled bytecode of a Python module. When a module is imported, CPython compiles the source to bytecode and saves it so that later imports can skip the compilation step. This speeds up start-up, not execution. Bytecode can also be produced explicitly with the py_compile and compileall modules, and .pyc files can be run without the .py source when placed directly next to the importing code.

Structure

Since Python 3.2 (PEP 3147), cached files are stored in a __pycache__ directory with the interpreter version in the name, for example module.cpython-311.pyc. The file starts with a header containing a magic number that identifies the bytecode version, flags, and either a source modification time and size or a hash of the source (PEP 552, Python 3.7 and later). The rest is a code object serialized with the marshal module.

The format is an implementation detail of CPython. It is not stable between Python versions, so a .pyc generated by one version generally cannot be loaded by another, and other implementations such as PyPy use different bytecode.

Preservation And Security Notes

Treat .pyc files as disposable caches that can be regenerated from source; keep the .py files and note the Python version. Distributing only bytecode is not a reliable way to protect source code, as decompilers exist. Because marshal data is not designed to be safe against malicious input, unknown .pyc files should be treated as executable code and never loaded from untrusted sources.

Further Reading

  • py_compile module (Python documentation): https://docs.python.org/3/library/py_compile.html
  • PEP 3147, PYC Repository Directories: https://peps.python.org/pep-3147/
  • marshal module (Python documentation): https://docs.python.org/3/library/marshal.html