Syntax checking python...

Trent Mick trentm at ActiveState.com
Fri Jan 31 23:58:41 EST 2003


[Afanasiy wrote]
> 
> In other languages, I can receive syntax errors without the script having
> to execute. Please do not let this hurt your feelings. I merely bring up
> the other languages as an example of what I mean and what I am used to.
> 
> In Python, I will not receive a syntax error until the interpreter runs
> right into it. This is not very efficient for me during my development.
> 
> Is there a way I can be notified of my typos without having to run the
> interpreter up to those mistakes? That is my question. No smartasses.

Python's py_compile module can do what you are asking.

    >>> import py_compile
    >>> py_compile.compile("t.py")
      File "t.py", line 1
          print "asdf" +
                        ^
    SyntaxError: invalid syntax

There is a compileall.py script that takes a directory and compiles all
the Python files in it. This will report any syntax errors.

In neither of these cases are your Python scripts executed.  What you
probably want to do is write a small Python script that takes a
filename (your script) and compiles it with the py_compile module.
You will get a SyntaxError traceback (like above) for the first syntax
error in your module.

If you want other warnings you should look at PyChecker, as others have
suggested here. The current PyChecker *does* execute the top-level of
your code so it is not ideal. A version is in the works to not have to
execute code, but I don't know when that is due.  Note that this is
often not considered a problem because it is usually considered
unnecessary and bad form to have top-level Python code actually execute
anything. If you use the:
    if __name__ == "__main__":
        # do stuff here
mechanism then you will always be fine.

Trent

-- 
Trent Mick
TrentM at ActiveState.com





More information about the Python-list mailing list