Home > Mobile >  How to deconstruct a Python-like function call?
How to deconstruct a Python-like function call?

Time:04-02

Suppose I had a function call as a string, like "log(2, floor(9.4))". I want to deconstruct the call in a way that allows me to access the function name and arguments for the firstmost call and accurately deducts whether a function call as an argument is an argument or not.

For example, the arguments when deconstructing the string above would come to [2, floor(9.4)]

I've already tried to use some string parsing techniques (e.g. splitting on commas), but it doesn't appear to be working.

CodePudding user response:

You can use the ast module:

import ast

data = "log(2, floor(9.4))"
parse_tree = ast.parse(data)

# ast.unparse() is for 3.9  only.
# If using an earlier version, use the astunparse package instead.
result = [ast.unparse(node) for node in parse_tree.body[0].value.args]
print(result)

This outputs:

['2', 'floor(9.4)']

I pulled the value to iterate over from manually inspecting the output of ast.dump(parse_tree).

Note that I've written something a bit quick and dirty, since there's only one string to parse. If you're looking to parse a lot of these strings (or a larger program), you should create a subclass of ast.NodeVisitor. If you want to also make modifications to the source code, you should create a subclass of ast.NodeTransformer instead.

  • Related