How to find ast dictionary item in Python using xpath-like expressions

18 Views Asked by At

I'm generating some python code and want to modify it. Is there a way to navigate the AST (or specifically AST dictionaries) using some sort of path-syntax?

Lets say I have a dict created by something like this:

ast.parse("""{
    "bets": [
         {
              "bet_number": "something",
              ...
         }
    ]
}""")

... and I want to change the value of bet_number to instead refer to a variable. How would I do that?

My naive approach has been just iterating over the keys (skipping over how to find the bets list and selecting the specific list entry)

for key in bet_dict.keys:
    if typing.cast(ast.Constant, key).s == "bet_number":
         param_dict.values[param_dict.keys.index(key)] = ast.Name("my_variable")

But that is messy, and as I go further into the dict it gets even worse.

Edit: I'm aware of NodeTransformers (in fact, I'm using them to find the dictionary itself), but dont know how to apply them for this particular case, where the location in the AST matters.

0

There are 0 best solutions below