Language and Compiler Modules

py_compile

Compiles a single Python source file into a bytecode cache. It does not execute the module body. doraise=True makes compilation errors available as PyCompileError. Use a temporary directory for examples and do not assume generated bytecode is portable across interpreters.

Formal Syntax & Structure

python syntaxpython
import py_compile

Return Value

module

Module namespace available through import; import is a statement, not a value-returning expression.

Working Example

Example Snippetpython
import py_compilefrom pathlib import Pathfrom tempfile import TemporaryDirectorywith TemporaryDirectory() as d:    p = Path(d) / "demo.py"    p.write_text("total = 7\n")    cache = py_compile.compile(str(p), doraise=True)    print(Path(cache).suffix)
Python Reference