Re: [Pyparsing] Fwd: Returning an actual `list`
Brought to you by:
ptmcg
From: <pt...@au...> - 2017-11-03 12:30:11
|
---- Athanasios Anastasiou <ath...@gm...> wrote: > The second example is closer to what I am after, but there does not seem to > be a "return" on make_list (?). Is a return implied here? > If None is returned (which is what Python does as a default if no return statement is present), then pyparsing will retain the tokens passed in as the parsed data. Otherwise, pyparsing will replace the parsed data with whatever is returned by the parse action. (If you really want to return None, return [None]). This makes it easy to write parse actions that update the parsed tokens in place, such as when adding new named results. Here's an example that parses a hex number of the form "#xxxxxx" which could represent an RGB color tuple: hexnumber = pp.Word('#', pp.hexnums) hexnumber.addParseAction(lambda t: int(t[0][1:], 16)) color = "#7fff00" print(hexnumber.parseString(color).dump()) And it prints: [8388352] If we add a second parse action (which has no return statement, and thus returns None): def get_rgb(t): # update parsed tokens in-place, adding values for red, green, and blue int_value = t[0] int_value, t['b'] = divmod(int_value, 256) int_value, t['g'] = divmod(int_value, 256) int_value, t['r'] = divmod(int_value, 256) hexnumber.addParseAction(get_rgb) print(hexnumber.parseString(color).dump()) The parse tokens are updated in-place and we get: [8388352] - b: 0 - g: 255 - r: 127 (Note that you must use the dict-style access in the body of the parse action in order to set new results names.) -- Paul |