python: get the abstract syntax tree of imported function?

ⅰ亾dé卋堺 提交于 2019-12-13 12:00:23

问题


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!


回答1:


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.

Or 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 ...



回答2:


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.



来源:https://stackoverflow.com/questions/4812144/python-get-the-abstract-syntax-tree-of-imported-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!