How does python build its AST

Terry Reedy tjreedy at udel.edu
Fri Dec 7 17:29:10 EST 2007


"MonkeeSage" <MonkeeSage at gmail.com> wrote in message 
news:79c1f3ea-aeeb-4607-b30d-48ad51b52996 at x69g2000hsx.googlegroups.com...
|A quick question about how python parses a file into compiled
| bytecode. Does it parse the whole file into AST first and then compile
| the AST, or does it build and compile the AST on the fly as it reads
| expressions? (If the former case, why can't functions be called before
| their definitions?)

The direct answer is that names cannot be entered into namespaces and bound 
to objects to be looked up until the corresponding object is created by 
executing the corresponding code.  Compiling Python code creates the 
internal code needed to create Python objects, but only exceptionally 
creates Python objects in the process.  In particular, compiling a function 
may create code objects (since the code is a constant) referenced by the 
function creation code, but not function objects themselves.

A less direct answer is the Python is designed to by usable interactively. 
In CPython interactive mode, you enter and the interpreter compiles and 
executes one top(module)-level statement at a time.  Calling a function you 
have not yet entered would be magical.

Terry Jan Reedy






More information about the Python-list mailing list