Python switch for syntax checking

Craig Ringer craig at postnewspapers.com.au
Fri Nov 19 15:18:13 EST 2004


On Sat, 2004-11-20 at 02:46, Jeff Duffy wrote:
> Hi all.
> 
>   I've been wondering why python itself doesn't provide a switch to 
> check a file for valid syntax. I know that you can currently call
> 
> python -c "import py_compile; py_compile.compile(r'MyApp.py')"
> 
> but in order to manage this effectively you have to add a shell alias, 
> write a script, mess about with your editor, or what have you. This 
> becomes yet another small annoyance I'd like to get rid of. I'm also 
> aware of PyChecker and other lint like tools, but these run the code and 
> often I don't want that.

The talk of a new switch to import a module would do the job nicely. If
you just import your script as a module, you know it loads and the main
program runs. Just add the usual

if __name__ == '__main__':
    main(sys.argv)

so your code loads as a module without executing its normal functions,
and you have your syntax check plus a bit of other sanity checking (all
modules import, etc).

In the mean time, it's fairly trivial to:

python -c "import myscript"

and not significantly longer / more complex than some sort of check
flag. 

That said, I'm all in favour of unit tests to make sure your code
actually runs. Especially in Python, where things like late binding of
names means that you can't check at load time whether names exit, unit
tests are IMO the way to go.

pylint / pychecker may also be worth looking into.

--
Craig Ringer




More information about the Python-list mailing list