0

As the title says, is there a better way to check a Python source for syntax errors without the use of external modules?

I mean, in sense of a more Pythonic style or a more performant way.

def CheckSyntax(source, raw = False):
    lines = source.count("\n")
    source += "\nThis is a SyntaxError"  # add a syntax error to source, it shouldn't be executed at all
    try:
        exec source in {}, {}
    except SyntaxError, e:
        if e.lineno != lines + 2:
            if raw:
                return e
            else:
                return e.lineno, e.offset, e.text

EDIT: Ideally it would be performant enough for real-time syntax checking.

4
  • 3
    Why not use pylint? logilab.org/857 Commented Jul 29, 2011 at 12:33
  • Well, it's an external module, but could be an option. Thanks Commented Jul 29, 2011 at 12:53
  • Do you want to verify if your programs are syntactically correct before running them or are you writing some kind of validation tool? Commented Jul 29, 2011 at 13:11
  • It's some sort of development environment which should have realtime syntax-checking implemented. Commented Jul 29, 2011 at 13:17

1 Answer 1

6

exec doesn't sound like a particularly good idea. What if the script in question has side effects (e.g. creates or modifies files) or takes a long time to run?

Take a look at the compile function and the parser module.

Sign up to request clarification or add additional context in comments.

2 Comments

In the function, I intentionally add a SyntaxError to the source so only thy parser will run over the source when executing, and if there are no SyntaxErrors in the original source, it will raise one at the end for sure.
Using the compile - function is not as fast as the alternative way above. (Just some milliseconds ..)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.