How to process syntax errors

Terry Reedy tjreedy at udel.edu
Tue Oct 11 19:48:30 EDT 2016


On 10/11/2016 4:02 AM, Pierre-Alain Dorange wrote:

> Using this function, the code is "compiled".
> I do not think this function is often used and most python project
> simply use the interpreter (which do a small translation into byte-code
> to be faster and check syntax error before running interpretation

You seem to be confusing CPython with, for instance, simple BASIC 
interpreters that tokenized the code, translated keywords to function 
numbers, and did other 'small translations' before execution.

The CPython compiler lexes (tokenizes), ll(1) parses to a syntax tree, 
does some analysis and transformation of the tree, and translates it to 
the bytecode for an stack machine.  All done using standard compiler theory.

One can even ask compile() to stop with the syntax tree and return that 
instead of a code object.  One can then do one's own tree manipulation 
and even code generation.

> So yes there is a way to check "syntax error" before executing code
> (using compile function and exceptions) but it was not standard,
 >  nor widely used...

In CPython, the built-in Python-visible compile function *is* the 
CPython compile function used to compile *all* python code.  Leaving out 
interaction with the OS and initialization, one could loosely define 
CPython as exec(compile(open('x.py').read())).

-- 
Terry Jan Reedy




More information about the Python-list mailing list