Raise A Custom Exception In Pyparsing
I have defined these as part of my grammar in pyparsing argument = oneOf(valid_arguments) function_name = oneOf(valid_functions) function_call = Group(function_name + LPAR + argume
Solution 1:
You can raise any kind of exception within a parse action, but to get the exception to get reported all the way back to your calling code, have your exception class derive from ParseFatalException. Here is your example with your requested special exception types.
from pyparsing import *
classInvalidArgumentException(ParseFatalException):
def__init__(self, s, loc, msg):
super(InvalidArgumentException, self).__init__(
s, loc, "invalid argument '%s'" % msg)
classInvalidFunctionException(ParseFatalException):
def__init__(self, s, loc, msg):
super(InvalidFunctionException, self).__init__(
s, loc, "invalid function '%s'" % msg)
deferror(exceptionClass):
defraise_exception(s,l,t):
raise exceptionClass(s,l,t[0])
return Word(alphas,alphanums).setParseAction(raise_exception)
LPAR,RPAR = map(Suppress, "()")
valid_arguments = ['abc', 'bcd', 'efg']
valid_functions = ['avg', 'min', 'max']
argument = oneOf(valid_arguments) | error(InvalidArgumentException)
function_name = oneOf(valid_functions) | error(InvalidFunctionException)
# add some results names to make it easier to get at the parsed data
function_call = Group(function_name('fname') + LPAR + argument('arg') + RPAR)
tests = """\
avg(abc)
sum(abc)
avg(xyz)
""".splitlines()
for test in tests:
ifnot test.strip(): continuetry:
print test.strip()
result = function_call.parseString(test)
except ParseBaseException as pe:
print pe
else:
print result[0].dump()
print
prints:
avg(abc)
['avg', 'abc']
- arg: abc
- fname: avg
sum(abc)
invalid function'sum' (atchar4), (line:1, col:5)
avg(xyz)
invalid argument 'xyz' (atchar8), (line:1, col:9)
Post a Comment for "Raise A Custom Exception In Pyparsing"