pyparsing actinos (WAS: Inverse of id()?)

Steven Bethard steven.bethard at gmail.com
Mon May 21 12:55:29 EDT 2007


Paul McGuire wrote:
> For instance, Seo Sanghyeon (I believe the same one now working on
> IronPython) uses the following technique in the EBNF parser/"compiler"
> that he contributed to the pyparsing examples directory:
> 
> # list of all the grammar variable names
> all_names = '''
> integer
> meta_identifier
> terminal_string
> ...
> '''.split()
> 
> # parse actions follow
> def do_integer(str, loc, toks):
>     return int(toks[0])

FWIW, I find that my actions never use anything but the token list, so 
to avoid writing a bunch of functions like the one above, I typically 
write::

     class ParseAction(object):
         def __init__(self, func):
             self.func = func
         def __call__(self, string, index, tokens):
             return self.func(*tokens)

     ...
     # parse an integer
     integer.addParseAction(ParseAction(int))
     ...
     # parse a relation object, passing appropriate strings
     # (or parsed objects) to the constructor
     relation.setParseAction(ParseAction(Relation))

I guess the integer/int and relation/Relation is a little redundant, but 
it's never bothered me too much.

STeVe



More information about the Python-list mailing list