s-expression parser in python

Paul McGuire ptmcg at austin.rr.com
Tue Apr 6 21:22:20 EDT 2010


On Apr 6, 7:02 pm, James Stroud <nospamjstroudmap... at mbi.ucla.edu>
wrote:
> Hello All,
>
> I want to use an s-expression based configuration file format for a
> python program I'm writing. Does anyone have a favorite parser?
>

The pyparsing wiki includes this parser on its Examples page:
http://pyparsing.wikispaces.com/file/view/sexpParser.py.  This parser
is also described in more detail in the pyparsing e-book from
O'Reilly.

This parser is based on the BNF defined here:http://
people.csail.mit.edu/rivest/Sexp.txt.  I should think Ron Rivest would
be the final authority on S-expression syntax, but this BNF omits '!',
'<', and '>' as valid punctuation characters, and does not support
free-standing floats and ints as tokens.

Still, you can extend the pyparsing parser (such is the goal of
pyparsing, to make these kinds of extensions easy, as the source
material or BNF or requirements change out from underneath you) by
inserting these changes:

real = Regex(r"[+-]?\d+\.\d*([eE][+-]?\d+)?").setParseAction(lambda
tokens: float(tokens[0]))
token = Word(alphanums + "-./_:*+=!<>")
simpleString = real | decimal | raw | token | base64_ | hexadecimal |
qString

And voila!  Your test string parses as:

[['and',
  ['or', ['>', 'uid', 1000], ['!=', 'gid', 20]],
  ['>', 'quota', 5000.0]]]

-- Paul



More information about the Python-list mailing list