I want to write a python function which checks syntax of a given python code.
So it must takes a string in parameter containing the code to check, and it returns a boolean indicating whether the code is syntactically correct or not.
My current function is :
def checker(code):
try:
exec(code)
return True
except:
return False
But when the given code contains infinite loops, the exec function will run forever. And if I timeout its execution, it will not see any syntax errors that could appear after the infinite loop.
I also tried to use the ast module, to parse the code into an ast, but it doesn’t detect every syntax error. I also got the same issue with the tokenize module, which parse the code into a list of tokens.
A simple error that pass both of these modules is True()
, which is detected as an error by the exec function.
Another function I tried is compile, but it doesn’t always raise an exception when it encounters an error, sometimes it raises a warning, and some of its warnings are not syntax errors but simple syntax warning like the ones exec could raise with a code like None is 1
.
So here is a syntactically incorrect minimal code that can’t be detected by any of the tools I tried :
while True:
pass
True()
There are solutions that takes a file as input to check its syntax (python -m py_compile [file]
, pychecker, pylint, etc), but I need the check to be processed programmatically since it is a part of a whole project, which needs to process it a lot of times.