get ast from python object in interpreter

丶灬走出姿态 提交于 2020-03-23 08:15:22

问题


I am building an application for which I would like a naive user to define a simple function. I would then like to take this function and convert it into an abstract syntax tree. This should also work during an interactive session (i.e using the interpreter). Here's what I have tried so far in the interpreter:

  • dill.source.getsource method
  • inspect.getsourcemethod
  • accessing the function object's __code__ attribute

The first two methods are problematic since they need for the function object to be written in a physical file somewhere in the system. The third one only gave me a byte code version of the code, not useable in ast.parse method.

I am also open to converting a python object directly to abstract syntax but this seems to go against how ast's are supposed to work.

I really need to be able to get an ast from my python object in a regular (not ipython) interpreter. How can I do this?

EDIT

Heres how my "naive user" would interact with my custom library through the interpreter:

>>> import MyLib
>>> def f(x): return x**2
>>> f = MyLib.FunctionAST(f) #FunctionAST will handld the conversion to abstract syntax

来源:https://stackoverflow.com/questions/60797338/get-ast-from-python-object-in-interpreter

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