Monday, October 10, 2016

Check Python Code for Syntax

A friend recommended I use Pylint to check my code for syntax errors.  Why not just run the code?  In complex code you can write a python module that cannot be run because it is part of a complex system.  You have to check your code into a code repository used by other people.  You want to check your code before checking it into the code repository.  But the Pylint program is not available for Windows.  It works on Linux systems, but the yum install tool finds all dependencies and installs everything needed to make Pylint work.  That does not happen in Windows, where you have to find and fix dependency after dependency.  You really cannot get Pylint to work on Windows, but you do not need to.

Say you want to check a file called my_python_program.py for syntax errors.  The trick is that importing a python module compiles that module, and the compilation finds all the syntax errors.  Here is what you do:  write a program called my_test.py that looks like this:


import my_python_program



print "***************"

print "finished test"
print "***************"

 Run this program and the first syntax error found will throw an exception.  Fix my_python_program.py and run my_test.py again.  When all the errors are fixed, the  program will print "finished test."  Now you can check-in your program into the code repository and know that it will not roll-over-and-die.  It might not work, but it will not die!

I launch the IDLE program, open the file through File > Open.  Then  in the file edit window I do Run > Run Module.  The output is printed in the IDLE shell window.

Update January 2017

A friend told me Pylint would catch some errors that compiling Python code would not catch.  It turns out he was right.  I was glad I used Pylint.  I said earlier that it is hard to test Python modules that are part of complex systems.  You could use the unittest unit testing framework from Python, which is patterned after JUnit for Java, but then you have to write the test code.  It is nice to have the budget and schedule to write test code, but that happens rarely.  When your code interacts with an external software system then you have to wait until you have access to the other system or must have a simulator for the other system.  A decent simulator is important for expensive and complex systems, but the simulator should be provided by the company supplying the external system.  The external system can be a networked hardware unit.  Getting good interface documentation (command messages and response messages) from the company providing the networked hardware or software is vital.  Remember that both the interface documentation and the simulator must be in the contract.  The other company cannot be relied upon to supply these unless they are contractually obligated to supply them.

Robert