I ran into the same problem. I tried to go like this: first, unscathed AST to some simpler view (dicton tree):
def simplify(node): if isinstance(node, ast.AST): res = vars(node).copy() for k in 'lineno', 'col_offset', 'ctx': res.pop(k, None) for k, v in res.iteritems(): res[k] = simplify(v) res['__type__'] = type(node).__name__ return res elif isinstance(node, list): return map(simplify, node) else: return node
and then you can just compare these views:
data = open("/usr/lib/python2.7/ast.py").read() a1 = ast.parse(data) a2 = ast.parse(data) print simplify(a1) == simplify(a2)
will give you True
EDIT
Just realized that there is no need to create a dict, so you can only do:
def compare_ast(node1, node2): if type(node1) is not type(node2): return False if isinstance(node1, ast.AST): for k, v in vars(node1).iteritems(): if k in ('lineno', 'col_offset', 'ctx'): continue if not compare_ast(v, getattr(node2, k)): return False return True elif isinstance(node1, list): return all(itertools.starmap(compare_ast, itertools.izip(node1, node2))) else: return node1 == node2
source share