I'm using the compiler
module found in python 2.7 to get the abstract syntax tree from a python program, and I want to extend the set of AST nodes with my own nodes.
For example, given the python program 1+2
, when parsed, the AST given from the compiler
module outputs:
Parser program:
import compiler
ast = compiler.parse("1+2")
print ast
Output:
Module(None, Stmt([Discard(Add((Const(1), Const(2))))]))
Now, I wish to extend the AST library with boolean nodes. Currently the compiler
module assigns True
, False
, as Name()
nodes. i.e. compiler.parse("True")
outputs Module(None, Stmt([Discard(Name('True'))]))
My plan is to construct a class named Bool
, and wrap nodes with boolean values, stripping those Name()
nodes and using my Bool
nodes instead. My Bool definition.
class Bool():
def __init__(self,expr):
self.expr = expr
Question, when printing the ast now, after correct substitution, it does not print in the similar style as the other nodes. Instead it gives for
compiler.parse("True")
It outputs
Module(None, Stmt([Discard(<Bool instance at 0x10e4306c8>)]))
Instead, what practice can I use to print those Bool
nodes in similar fashion as how the compiler
module does? e.g. desire:
Module(None, Stmt([Discard(Bool('True'))]))