brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -m compileall for a quick syntax check of a whole project

Python
~/tips/tip-python-compileall-syntax-check

python -m compileall -q src/

Compiles every Python file in a folder and reports files with syntax errors.

Before I deploy a Python project I like a cheap check that every file at least parses. The standard library has a module for it.

compileall compiles the source files in the directories you give it, recursively, and prints the ones with errors:

python -m compileall -q src/

With a broken file in the tree the output looks like this:

*** Error compiling 'src/pkg/bad.py'...
  File "src/pkg/bad.py", line 1
    def f(:
          ^
SyntaxError: invalid syntax

The options from the docs: -q prints only errors, -qq silences all output, -f forces a rebuild even if timestamps are up to date, -x regex skips files whose path matches, and -j N uses N workers (0 means one per CPU). A version for a whole project that skips a virtual environment:

python -m compileall -q -f -j 0 -x '/\.venv/' .

The docs do not document an exit status for the command line. On Python 3.11 here it exits with 1 when a file fails, which makes it usable in a CI step, but check that on your version. Inside Python, compile_dir() returns a false value when something failed.

Caveats: it writes __pycache__ folders, so run it on a checkout you do not mind that for. And it only proves the code parses. A typo in a variable name still passes, so treat it as a smoke test that sits next to your real tests.

Further reading: compileall documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link