Unable to parse function declaration with Python like syntax

243 views Asked by At

I am using pyPEG to parse the declaration of a function. Currently I have this written:

from pypeg2 import attr, \
                   optional, \
                   csl, \
                   name, \
                   List, \
                   Namespace


class Parameters(Namespace):
    grammar = optional(csl(name()))


class Function(List):
    grammar = "def", name(), \
              "(", attr("params", Parameters), "):"

So for example if I do:

>>> import pypeg2
>>> f = pypeg2.parse("def f(a, b):", Function)

I would expect f.params to contain a and b as parameters. Instead:

>>> f.params
Parameters([], name=Symbol('b'))

only b is found. Why is b the only found symbol?

1

There are 1 answers

0
colinfang On

Because name() essential attach a matched Symbol to the name attr of the class. In your case the attachment of b overwrites a.

The official doc lists the following:

class Parameter(object):
    grammar = attr("typing", Type), name()

class Parameters(Namespace):
    grammar = csl(Parameter)

Here each Parameter has a name. The Parameters looks for the name attribute of the matched Parameter and put it into is internal dict.