Python 2.6a2: Compile ASTs from within Python code
I’m not going to go into too much depth because Georg Brandl has already covered it, but it’s an interesting topic. I couldn’t help but write a little entry about it.
A new alpha of Python has just been released, including a patch I wrote for compiling Python Abstract Syntax Trees down to bytecode. This means it’s now possible to manipulate ASTs from within your Python program, which lets you do all sorts of crazy things - like this, for example.
Piping this little program into itself yields the following:
$ ./python wacky.py <wacky.py
Bwahaha! I was once an Assign node!
Bwahaha! I was once an Assign node!
Neat huh?
Anyway, since then - on Neal Norwitz’s advice - I’ve started on an experimental patch for what I hope will one day be an optimizer for Python ASTs. Even though it’s early days, the possibilities offered by optimizing at the AST level are very interesting. For example, the (dirty, filthy, ugly, hack of a) patch I’m working on at the moment has support for optimizing this code:
if 1:
'true'
else:
'false'
Down to this (remember, no bytecode has been generated yet):
'true'
Very, very exciting stuff.
Anyway, I have a train to catch. More on this when I have more to show!