py_compile compiles one file, while compileall walks directories. Both find syntax errors without importing a module, making them useful as a quick check before broader tests.
Practical example
from pathlib import Path
import py_compile
source = Path("example_module.py")
source.write_text("answer = 42\n", encoding="utf-8")
try:
py_compile.compile(source, doraise=True)
print("syntax is valid")
finally:
source.unlink(missing_ok=True)
Fail explicitly
In the example, doraise=True turns failure into PyCompileError. On the command line, run python -m compileall -q src and inspect the exit code in CI.
What pycache contains
.pyc files hold bytecode associated with interpreter version and invalidation rules. They are a cache, not a source distribution format or code protection.
Scope of the check
Successful compilation does not find missing runtime names, incorrect types, or integration failures. Combine it with tests and static analysis appropriate for the project.
Keep learning
Strengthen the foundation with error handling in Python. The official Python documentation, accessed July 22, 2026, documents the API, limitations, and version differences.