开发者

python: get the abstract syntax tree of imported function?

开发者 https://www.devze.com 2023-02-07 03:22 出处:网络
Let\'s say I\'ve already imported a python module in the interpreter. How can I get the abstract syntax tree of the impor开发者_高级运维ted module (and any functions and classes within it) within the

Let's say I've already imported a python module in the interpreter. How can I get the abstract syntax tree of the impor开发者_高级运维ted module (and any functions and classes within it) within the interpreter? I don't want to have to re-parse the source files. Thanks!


Maybe you find some inspiration in this recipe:

  • http://code.activestate.com/recipes/533146-ast-pretty-printer/

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). \n\nThis module provides ...

Python 3:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消