Search code examples
pythonpyparsing

PyParsing: how to parse a function call and returning it as string


From here I have this code to parse a function call:

functionName = Word(alphanums + '_')
functionBody = Forward()
functionBody <<= functionName + (Literal("(") + Optional( delimitedList ( functionBody | Word(alphanums + '_') | "''"),'') + Literal(")"))

But, when calling:

result = functionBody.parseString('function(param1,param2,param3)')

I got this result:

['function', '(', 'param1', 'param2', 'param3', ')']

Is there any way to get this result instead:

['function(param1, param2, param3)']

That is to say: parsing the function call is well written, but returning it as string instead of as an array without using the Python join sentence?


Solution

  • I thank Mr. PaulMcG, since he gave three possible answers in his comment, but I am posting a solution for somebody who might be needing it as well. originalTextFor did the trick for me:

    functionName = Word(alphanums + '_')
    functionBody = Forward()
    functionBody <<= originalTextFor(functionName + (Literal("(") + Optional( delimitedList ( functionBody | Word(alphanums + '_') | "''"),'') + Literal(")")))
    

    Now it is returning:

    ['function(param1,param2,param3)']