user3857330
user3857330

Reputation: 3

Getting Function name and arguments

I came up with this situation while writing code in python for my project and began to think on this problem.

The problem is given a string containing a function name with its arguments how do we get the arguments and the function name given the number of arguments in the function.

My first thought was:

s = 'func(a,b)'
index = s.find('(')
if(index != -1):
    arg_list = s[index+1:-1].split(',')
    func_name = s[:index]

But as I began to think more I realised what if function is specified within functions which has its own arguments?

func1(func2(a,b,c),func3(d,e))

With my above approach I will end up with right function name but arg_list will contain

["func2(a","b","c)","func3(","d","e)"]

How to generically solve this situation?

Upvotes: 0

Views: 551

Answers (2)

Robᵩ
Robᵩ

Reputation: 168716

If your language looks sufficiently like Python, use ast.parse():

import ast

def parse(s):
  tree = ast.parse(s)
  print ast.dump(tree)

parse('f(a,b)')

All the information you need will be encoded in tree.

Upvotes: 1

Dan Oberlam
Dan Oberlam

Reputation: 2496

>>> import pyparsing as pyp  
>>> def get_name_and_args(a_string):
    index = a_string.find('(')
    if index == -1:
        raise Exception("No '(' found")
    else:
        root_function, a_string = a_string[:index], a_string[index:]
        data = {}
        data[root_function] = pyp.nestedExpr().parseString(a_string).asList()[0][0].split(',')
        return data   

>>> print get_name_and_args("func(a,b)")
{'func': ['a', 'b']}

This solves the simpler example you gave using the pyparsing module. I wasn't sure exactly how you wanted the output formatted, and it doesn't work for the nested example. However this should be enough to get you started

Upvotes: 1

Related Questions