Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to deconstruct a Python-like function call?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading