Accessing AST at runtime

  • Thread starter alessandromoura35
  • Start date
A

alessandromoura35

Hi,

I would like to access the AST of a python object at runtime. I mean, if I have this:

def f(x): return x*x/2

Is there any way to interrogate the object f to find out the AST of the expression x*x/2 ? Of course if the definition of f were in a file, I could use the ast module to parse it; but what I want is to do this from within the code.

The closest thing I was able to find was f.__code__, and more specifically f.__code__.co_code, but that is a byte-string which seems to be the bytecode (?) for the function.

This may not be possible at all; maybe after the def statement is processed by the Python interpreter the AST information is discarded. But I wanted to check here if someone knows one way or another.

Many thanks.
 
R

Ramchandra Apte

Hi,



I would like to access the AST of a python object at runtime. I mean, if I have this:



def f(x): return x*x/2



Is there any way to interrogate the object f to find out the AST of the expression x*x/2 ? Of course if the definition of f were in a file, I could use the ast module to parse it; but what I want is to do this from within the code.



The closest thing I was able to find was f.__code__, and more specifically f.__code__.co_code, but that is a byte-string which seems to be the bytecode (?) for the function.



This may not be possible at all; maybe after the def statement is processed by the Python interpreter the AST information is discarded. But I wanted to check here if someone knows one way or another.



Many thanks.

You could scan the text for code and then ast.parse() it.
Then you know how...
 
T

Terry Reedy

Hi,

I would like to access the AST of a python object at runtime. I mean,
if I have this:

def f(x): return x*x/2

Is there any way to interrogate the object f to find out the AST of
the expression x*x/2 ? Of course if the definition of f were in a
file, I could use the ast module to parse it; but what I want is to
do this from within the code.

The closest thing I was able to find was f.__code__, and more
specifically f.__code__.co_code, but that is a byte-string which
seems to be the bytecode (?) for the function.

This may not be possible at all; maybe after the def statement is
processed by the Python interpreter the AST information is discarded.

Yes, it is.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top