0

I'm looking for a way to extract arguments embedded into python function returned to me as strings.

For example:

'create.copy("Node_A", "Information", False)'
# expected return: ["Node_A", "Information", "False"]

'create.new("Node_B")'
# expected return: ["Node_B"]

'delete("Node_C")'
# expected return: ["Node_C"]

My first approach was regular expressions like this:

re.match(r"("(.+?")")

But it returns None all the time.

How can I get list of this arguments?

BTW: I'm forced to use Python 2.7 and only built-in functions :(

1
  • All of your strings would be syntax errors. Please provide valid data and regex. Commented Sep 25, 2021 at 15:12

3 Answers 3

1

You can parse these expressions using the built-in ast module.

import ast

def get_args(expr):
    tree = ast.parse(expr)
    args = tree.body[0].value.args
    
    return [arg.value for arg in args]

get_args('create.copy("Node_A", "Information", False)') # ['Node_A', 'Information', False]
get_args('create.new("Node_B")') # ['Node_B']
get_args('delete("Node_C")') # ['Node_C']
Sign up to request clarification or add additional context in comments.

Comments

0

Here an example without any external modules and totally compatible with python2.7. Slice the string w.r.t. the position of the brackets, clean it from extra white-spaces and split at ,.

f = 'create.copy("Node_A", "Information", False)'
i_open = f.find('(')
i_close = f.find(')')

print(f[i_open+1: i_close].replace(' ', '').split(','))

Output

['"Node_A"', '"Information"', 'False']

Remark:

  • not for nested functions.

  • the closing bracket can also be found by reversing the string

    i_close = len(f) - f[::-1].find(')') - 1

Comments

0

See below (tested using python 3.6)

def get_args(expr):
    args = expr[expr.find('(') + 1:expr.find(')')].split(',')
    return [x.replace('"', '') for x in args]


entries = ['create.copy("Node_A", "Information", False)', "create.new(\"Node_B\")"]
for entry in entries:
    print(get_args(entry))

output

   ['Node_A', ' Information', ' False']
   ['Node_B']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.