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
methodinspect.getsource
method- 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
decompile
? I can't find it anywhere?? Could you give an example? – Godlessast.dump(ast.parse(inspect.getsource(f)))
does work when usingipython
. It doesn't work in normal python shell becauselinecache.cache
is empty there. If you expect the user to interact in a shell, doesn't it make more sense to use an interactive one? – Nodaldill.source.getsource
in a python shell, and it works as expected:ast.dump(ast.parse(dill.source.getsource(f)))
. Apparently,inspect.getsource
doesn't work for objects which are defined interactively. Reference and python bug – Nodaldill.source.getsource
does not work for me and returnsOSError: could not extract source code
. Are you sure you're not using ipython? What version ofdill
are you using? – Godless3.6.8
anddill==0.3.1.1
. And, yes I am sure that I am in python shell because I tested it again. Check here. – Nodal