0

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?

  • Could you potently use some sort of loop or recursion to do what you have already done. By telling it to find the next `(` and so on. Not sure if it will work but I think it could. – bobthemac Jul 24 '14 at 22:40
  • 3
    So you're trying to parse functions from a string `func(a,b)` and be able to return the function name `func` and the parameters `[a, b]`? Consider using a parsing module such as pyparsing (example here) http://stackoverflow.com/a/21081531/3076272 – Dan Oberlam Jul 24 '14 at 22:40
  • 3
    Use a regular expression – KurzedMetal Jul 24 '14 at 22:40
  • regex is probably the way to go with this for ease – bobthemac Jul 24 '14 at 22:46

2 Answers2

1
>>> 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

Dan Oberlam
  • 2,435
  • 9
  • 36
  • 54
1

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.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308