Friday, June 6, 2008

Syntax Check

When working on anything important, it makes sense to check the syntax of your file before setting it live. This is usually accomplished with a simple command-line flag. Consider the following:

travis@travis-ubuntu:/home/travis% ruby -c test.rb
Syntax OK

travis@travis-ubuntu:/home/travis% perl -c syntax OK

travis@travis-ubuntu:/home/travis% php -l test.php
No syntax errors detected in test.php

Python doesn't make this as easy. I'm not sure why because it seems to have a pretty well defined separation between it's compiler and runtime, but the general consensus is to break your code into classes and just have a single "main" file for your runtime code. That way you can just run python filename, which will compile the file to bytecode as well as check syntax; however, this is frustrating if you just want to check the syntax and not actually run the program (common with DB applications). Consider the following hack an alternative, which could easily be wrapped up in a helper shell script.

python -c "import py_compile; py_compile.compile('')"

This produces no output on success and an error on failure. It has the possibly unwanted side effect of compiling to bytecode, but I don't think there's any getting around that.


Steve Laniel said...

It lacks the power of a full compiler, but try pyflakes as well.

Anonymous said...

you mean a helper like:
python -m py_compile