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.
-
3Why not use pylint? logilab.org/857S.Lott– S.Lott2011年07月29日 12:33:24 +00:00Commented Jul 29, 2011 at 12:33
-
Well, it's an external module, but could be an option. ThanksNiklas R– Niklas R2011年07月29日 12:53:58 +00:00Commented Jul 29, 2011 at 12:53
-
Do you want to verify if your programs are syntactically correct before running them or are you writing some kind of validation tool?brandizzi– brandizzi2011年07月29日 13:11:24 +00:00Commented Jul 29, 2011 at 13:11
-
It's some sort of development environment which should have realtime syntax-checking implemented.Niklas R– Niklas R2011年07月29日 13:17:20 +00:00Commented Jul 29, 2011 at 13:17
1 Answer 1
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?
answered Jul 29, 2011 at 12:36
NPE
503k114 gold badges970 silver badges1k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Niklas R
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
Using the compile - function is not as fast as the alternative way above. (Just some milliseconds ..)
Explore related questions
See similar questions with these tags.
lang-py