You are looking for the ast
module, which lets you analyse and traverse the abstract syntax tree of python code.
The compile()
function lets you compile a python source file into a AST, but the module itself provides a helper function too, ast.parse()
:
import ast
with open(sourcefilename, 'r') as source:
tree = ast.parse(source.read(), sourcefilename)
Someone wrote an e-book on Python AST wrangling: Green Tree Snakes - the missing Python AST docs that you might find interesting.