Search code examples
pythonsyntax-errorsyntax-checking

Is there a better way to check Python code for a syntax errors without external modules?


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.


Solution

  • 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.