Accessing Python parse trees

Lonnie Princehouse finite.automaton at gmail.com
Thu Mar 3 20:15:28 CET 2005


No.  I don't think it's possible to read the parse tree used by the
interpreter, especially as it is being created. Here are a couple of
kludgy ideas that might come close, though:

1. Use introspection to have your on_parsing function locate the and
parse the code being executed.  I'm not sure if you'll be able to
figure out _exactly_ where on_parsing is being called from (e.g. you
can probably only narrow it down to the statement, not the expression),
but you should be able to come close enough to be useful.  The inspect
module and sys._getframe will come in handy.  Note that this won't work
if you can't retrieve the source (as is the case with exec/eval)

2. Or, using the code module, start up your own interpreter inside of
the interpreter.  Intercept and parse lines of source as they are fed
to this interpreter.

On a side note, check out the compiler module.  You might find it to be
friendlier and more useful than parser.




More information about the Python-list mailing list