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.

AndyG
  • 39,700
  • 8
  • 109
  • 143
Niklas R
  • 16,299
  • 28
  • 108
  • 203

1 Answers1

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 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. – Niklas R Jul 29 '11 at 12:40
  • Using the compile - function is not as fast as the alternative way above. (Just some milliseconds ..) – Niklas R Jul 29 '11 at 12:53