[TransWarp] fmtparse - named rules

Oleg Broytmann phd at work.phd.pp.ru
Mon Jun 16 05:15:47 EDT 2003


   How should I use Named rules?

from peak.util.fmtparse import *

cmp_func = Named("cmp_func",
    Alternatives("eq", "neq", "lt", "le", "gt", "ge", "like"))

test1 = "eq"
print parse(test1, cmp_func)

   Prints {}. Oops, where is my name?

   The following is better:

between_expr = Sequence("between", '(', Named("name"), ',', Named("value1"), ',', Named("value2"), ')')

test2 = "between(month,1,12)"
print parse(test2, between_expr)

   It prints {'name': 'month', 'value1': '1', 'value2': '12'}. Ok. But

between_expr = Named("between", Sequence("between", '(', Named("name"), ',', Named("value1"), ',', Named("value2"), ')'))

test3 = "between(month,1,12)"
print parse(test3, between_expr)

   Prints {'between': ('value2', '12')}. Ouch, where is name and value1? It
seems I am doing it wrong way, but what is the right way?

   Returning to the very first exampl... I can use ExtractString:

cmp_func = Named("cmp_func",
    ExtractString(Alternatives("eq", "neq", "lt", "le", "gt", "ge", "like")))

test4 = "eq"
print parse(test4, cmp_func) # => {} Oops, where is my name?

   {'cmp_func': 'eq'} - ok, exactly what I wanted... but this:

between_expr = Named("between", ExtractString(Sequence("between", '(', Named("name"), ',', Named("value1"), ',', Named("value2"), ')')))

test5 = "between(month,1,12)"
print parse(test5, between_expr)

   {'between': 'between(month,1,12)'}. ExtractString extracted too much...

     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.

More information about the PEAK mailing list