def conditionAsParseAction(fn, message=None, fatal=False): msg = coalesce(message, "failed user-defined condition") exc_type = ParseFatalException if fatal else ParseException fn = wrap_parse_action(fn) @wraps(fn) def pa(t, l, s): if not bool(fn(t, l, s)[0]): raise exc_type(s, l, msg) return t return pa
def addCondition(self, *fns, message=None, callDuringTry=False, fatal=False): """ Add a boolean predicate function to expression's list of parse actions. See `setParseAction` for function call signatures. Unlike ``setParseAction``, functions passed to ``addCondition`` need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException """ def make_cond(fn): def cond(token, index, string): result = fn(token, index, string) if not bool(result.tokens[0]): if fatal: Log.error( "fatal error", casue=ParseException(token.type, index, string, msg=message), ) raise ParseException(token.type, index, string, msg=message) return token return cond output = self.copy() for fn in fns: output.parseAction.append(make_cond(wrap_parse_action(fn))) output.set_config( callDuringTry=self.parser_config.callDuringTry or callDuringTry) return output
def __init__(self, methodCall): self.callable = wrap_parse_action(methodCall) self.called = False