On this page
  1. compileall
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Pre-Compiling in CI or Container Builds
  7. Gotchas & Boundaries
  8. Common Functions

compileall

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


Import

import compileall

Overview

Batch bytecode compiler for entire directory trees (compile_dir(), compile_file(), compile_path()), also runnable as python3 -m compileall. Use compileall in Docker builds, packaging steps, or CI checks to pre-generate .pyc files (reducing cold-start time) and catch SyntaxError across every module at once.

Quick Start

import compileall
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    src = Path(tmp) / "hello.py"
    src.write_text("x = 1 + 2\n", encoding="utf-8")

    ok = compileall.compile_dir(tmp, quiet=1)
    assert ok is True
    assert list((Path(tmp) / "__pycache__").glob("hello.*.pyc"))

Implementation Walkthrough

1. Pre-Compiling in CI or Container Builds

Run compileall with workers=0 (auto-detect CPU count) and quiet=1 (print errors only) to validate syntax and bake optimized bytecode:

import compileall

def precompile_tree(root: str) -> bool:
    return compileall.compile_dir(
        root,
        maxlevels=10,
        force=False,
        quiet=1,
        optimize=1,   # strips asserts and __debug__ blocks
        workers=0,
    )

Gotchas & Boundaries

Common Functions

Linked from

Related notes