Python SyntaxError
Compile a small piece of source to distinguish invalid syntax from a failure during execution.
A simple example
SyntaxError
- Start with Python text with an unclosed parenthesis
- Do this Compile the text
- Result Syntax error
Syntax
compile(source, filename, "exec")
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyIdentify a syntax error in a saved rule
A saved rule is read back before it can be applied to new records. Distinguish a mistake in the rule's syntax from a failure that happens later when valid code is running.
source = "if total > 5 print(total)"
try:
compile(source, "receipt_rule.py", "exec")
except SyntaxError as problem:
print(f"{problem.filename}, line {problem.lineno}")
receipt_rule.py, line 1
The rule is missing a colon. Compilation detects the error before the rule can execute.
Review a student’s display line
A pupil double-checks a complete print statement before a demo. Check the example source before running any statements. Will the Python version parse?
Catch a missing parenthesis
An editor saves an unfinished statement from a classroom script. Check the example source before running any statements. Will the Python version parse?
What to watch for
Python exposes a SyntaxError exception. PHP reports parse diagnostics using its own error categories.