If I have a string of Python code, how do I tell if it is valid, i.e., if entered at the Python prompt, it would raise a SyntaxError or not? I thought that using compiler.parse would work, but apparently that module has been removed in Python 3. Is there a way to do it that also works in Python 3. Obviously, I don't want to execute the code, just check its syntax.
19
votes
2 Answers
23
votes
Use ast.parse:
import ast
def is_valid_python(code):
try:
ast.parse(code)
except SyntaxError:
return False
return True
>>> is_valid_python('1 // 2')
True
>>> is_valid_python('1 /// 2')
False
3
votes
The compiler module is now a built-in.
compile(source, filename, mode[, flags[, dont_inherit]])Compile the source into a code or AST object. Code objects can be executed by an exec statement or evaluated by a call to eval(). source can either be a string or an AST object. Refer to the ast module documentation for information on how to work with AST objects.
The AST parser is now a seperate module.
ast.parse(expr, filename='<unknown>', mode='exec')Parse an expression into an AST node. Equivalent to
compile(expr, filename, mode, ast.PyCF_ONLY_AST).
gccdid not have a Python frontend and static compilers in general sucked at doing dynamic languages, if they even tried. - user395760g==5without setting a value for g) asg==5will ast.parse even with no g anywhere - Joran Beasley