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.
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
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
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:
then I would like to make a callback:
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:
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:
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