On this page
  1. py_compile
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Checking Syntax Programmatically
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

py_compile

Prev: pwd | Up: stdlib_module | Next: pyclbr
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — py_compile
Tags: #public #python3 #stdlib


Import

import py_compile

Overview

Single-file Python source-to-bytecode compiler (py_compile.compile()), underlying compileall. Use py_compile when you want programmatic control over compiling one .py file into a .pyc artifact, choosing an output path, or validating syntax with doraise=True.

Quick Start

from pathlib import Path
import py_compile
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    src = Path(tmp) / "mod.py"
    src.write_text("def add(a, b): return a + b\n", encoding="utf-8")

    pyc_path = py_compile.compile(str(src), doraise=True)
    assert Path(pyc_path).exists()

Implementation Walkthrough

1. Checking Syntax Programmatically

Pass doraise=True so syntax errors raise py_compile.PyCompileError instead of merely printing to sys.stderr:

from pathlib import Path
import py_compile
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    bad = Path(tmp) / "broken.py"
    bad.write_text("def broken(:\n    pass\n", encoding="utf-8")

    try:
        py_compile.compile(str(bad), doraise=True)
        assert False, "expected PyCompileError"
    except py_compile.PyCompileError as exc:
        assert "broken.py" in exc.msg

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes