Michael Cohen - 2016-01-17

I like that you can set a name for a match using setResultName() on the elements but when I come to using this in the setParserAction() callback this is fiddly in the case where the element might not be there.

For example, say I have something like:

Optional( Keyword("foo").setResultName("foo"))

then I would like to make a callback:

def callback(tokens):
   return SomeClass(foo=tokens.foo)

But this does not work because if it is there tokens.foo returns another ParseResult() instance which means I need to deref the 0th element:

def callback(tokens):
   return SomeClass(foo=tokens.foo[0])

And if it is not there the getattr returns and empty string which will cause this to blow up with an IndexError. So I need to do something like:

def callback(tokens):
   if token.foo is ""
     foo = None
   else:
     foo = tokens.foo[0]

   return SomeClass(foo=foo)

It would be so much easier if the getattr returns an empty result set for an unknown attribute or if getattr just returns the first element of the match (if I need a repeated match I can just use the dict access form).

 

Last edit: Michael Cohen 2016-01-17