python: get the abstract syntax tree of imported function?

Question:

Let’s say I’ve already imported a python module in the interpreter. How can I get the abstract syntax tree of the imported module (and any functions and classes within it) within the interpreter? I don’t want to have to re-parse the source files. Thanks!

Answers:

Maybe you find some inspiration in this recipe:

A function that outputs a human-readable version of a Python AST.

Python 2 option (as compiler is removed in Python 3): Use compiler combined with inspect (which, of course, still uses the source):

>>> import compiler, inspect
>>> import re # for testing 
>>> compiler.parse(inspect.getsource(re))
Module('Support for regular expressions (RE). nnThis module provides ...

Python 3:

>>> import ast, inspect
>>> ast.parse(inspect.getsource(re))
<_ast.Module at 0x7fdcbd1ac550>
Answered By: miku

There doesn’t seem to be a way to get an AST except from source code. If you explain why you don’t want to re-parse the source files, maybe we can help with that.

Answered By: Ned Batchelder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.