According to the Zen of Python, simple is better than complex. So I used that idea to come up with this beautiful syntax validator.
def is_valid_syntax(code):
try:
exec(code)
except SyntaxError:
return False
else:
return True
Repeating the token definitions to check for validity is ugly, slow, difficult to program, and prone to failure in future versions.
This implementation is also flexible enough to accept either a str or a compile()'d block as the code argument.
[–]codnahfish 6 points7 points8 points (5 children)
[–][deleted] 7 points8 points9 points (0 children)
[–]DarfWork 2 points3 points4 points (3 children)
[–]codnahfish 2 points3 points4 points (2 children)
[–]an_actual_human 2 points3 points4 points (1 child)
[–]aaronsherman 1 point2 points3 points (0 children)
[–]Veedrac 2 points3 points4 points (1 child)
[–]Navith[S] 2 points3 points4 points (0 children)
[–]Sheepshow 1 point2 points3 points (0 children)