Iterate AST
I have this python code as an example
def myFunction(x):
return filters.delta(x)
if starting:
diagnostics.debug(myFunction(1))
diagnostics.debug(myFunction(2))
filters.delta
is a utility function that users of my application can use in their python scripts. Above the code should be output
0 0
But it outputs
0 1
This is because my script helper is too dumb for the above, the real parameters for the function filter.delta
filters.delta(x, indexer)
my dumb drug just add the name of the parameters. So after preparation, the above code will look like
def myFunction(x):
return filters.delta(x, "x")
This will call both calls myFunction
using the same indexer, and on the second, overwrite the patterns for the first call. So my goal is to use the AST module to parse the synstax tree and add an indexer to all the functions in the chain. The result should look like
def myFunction(x, indexer):
return filters.delta(x, indexer)
if starting:
diagnostics.debug(myFunction(1, "1"))
diagnostics.debug(myFunction(2, "2"))
Using ast mode I can dump the script to a tree like
import ast tree = ast.parse(script)
But I haven't found any information on how to iterate through the tree, and when I find a function of the type filters.delta
that needs preparation, I will repeat the request and add an argument to all function calls. Is it possible somehow?
Here is a real world example where this software is used to
def filterAndroidSignal(axis):
return filters.deadband(filters.continuousRotation(axis), 0.1)
def onUpdate():
vJoy[0].x = filterAndroidSignal(android[0].yaw)
vJoy[0].y = filterAndroidSignal(android[0].pitch)
if starting:
android[0].update += onUpdate
The above code will work differently from my other example, because it filters.continuousRotation
will be indexed by"axis"
We do all of this because our target users are not programmers, they are gamers and VR enthusiasts, and we need a simple scipting mechanism.
http://andersmalmgren.github.io/FreePIE/
Update: I have simplified the test script to this
def myFunction(x):
return filters.delta(x)
myFunction(1)
If I post this script via ast.parse I get an object of type _ast.Module
. The first level seems straightforward, it contains a list of two elements: def def functions and an expression thatmyFunction(1)
Let's look at the expr expression, which is a functon call myFunction(1)
Not too obvious how I would go to the dec function above from it, and also the dec function should contain children on its own? It's not very obvious how to navigate
I think I need a guide to rethink this object structure or a tutorial on how to go through it. The biggest question right now is how can I navigate from _ast.Call
to_ast.FunctionDef
source to share
No one has answered this question yet
Check out similar questions: