Search code examples
pythonpython-3.xparsingpyparsing

pyparsing - How to parse commas to use in functions


So I am making a parser, but the program doesn't parse commas. For example:

>>> evaluate("round(pi)")
3

>>> evaluate("round(pi, 2)")
SyntaxError: Expected {{[- | +] {{{{{{{W:(ABCD..., ABCD...) Suppress:("(") : ...} Suppress:(")")} | 'PI'} | 'E'} | 'PHI'} | 'TAU'} | {Combine:({{W:(+-01..., 0123...) [{"." [W:(0123...)]}]} [{{'E' [W:(+-)]} W:(0123...)}]}) | Combine:({{{[W:(+-)] "."} W:(0123...)} [{{'E' [W:(+-)]} W:(0123...)}]})}}} | {[- | +] Group:({{Suppress:("(") : ...} Suppress:(")")})}}, found ','  (at
char 8), (line:1, col:9)

How can the program parse commas that are used in functions? My objective is that functions like round(pi, 2) returns 3.14, or log(10, 10) returns 1.0.


Solution

  • If you have a parser that parses a single integer in parentheses like this:

    LPAR, RPAR = map(Suppress, "()")
    integer = Word(nums)
    int_values = LPAR + integer + RPAR
    

    and you want to change it to accept a list of integers instead, you would write:

    int_values = LPAR + delimitedList(integer) + RPAR
    

    You would also probably use Group to keep these parsed values together logically:

    int_values = LPAR + Group(delimitedList(integer)) + RPAR