How can I make sure all my Python code "compiles"?

code-analysis, parsing, python

Solution

Look at PyChecker and PyLint.

Here's example output from pylint, resulting from the trivial program:

print a

As you can see, it detects the undefined variable, which py_compile won't (deliberately).

in foo.py:

************* Module foo
C:  1: Black listed name "foo"
C:  1: Missing docstring
E:  1: Undefined variable 'a'


...

|error      |1      |1        |=          |

Trivial example of why tests aren't good enough, even if they cover "every line":

bar = "Foo"
foo = "Bar"
def baz(X):
    return bar if X else fo0

print baz(input("True or False: "))

EDIT: PyChecker handles the ternary for me:

Processing ternary...
True or False: True
Foo

Warnings...

ternary.py:6: No global (fo0) found
ternary.py:8: Using input() is a security problem, consider using raw_input()

Problem

My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages. When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-specific errors remain. For me that means that I can't rely solely on my runtime defense (rigorous testing of input, asserts etc.) to avoid crashes, because in 6 months when some otherwise nice code finally gets run, it might crack due to some stupid typo. Clearly a system should be tested enough to make sure all code has been run, but most of the time I use Python for in-house scripts and small tools, which ofcourse never gets the QA attention they need. Also, some code is so simple that (if your background is C/C++) you know it will work fine as long as it compiles (e.g. getter-methods inside classes, usually a simple return of a member variable). So, my question is the obvious - is there any way (with a special tool or something) I can make sure all the code in my Python script will "compile" and run?

Original source