Skip to content

Commit

Permalink
improve error management; shunt .run() with string to .eval()
Browse files Browse the repository at this point in the history
  • Loading branch information
newville committed Sep 29, 2024
1 parent cc1f757 commit 8d7326d
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions asteval/asteval.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,6 @@ def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None):
if expr is not None:
self.expr = expr
msg = str(msg)

err = ExceptionHolder(node, exc=exc, msg=msg, expr=self.expr, lineno=lineno)
self._interrupt = ast.Raise()

Expand All @@ -241,7 +240,13 @@ def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None):
exc = err.exc
if exc is None:
exc = Exception
raise exc(self.error_msg)
if len(err.msg) == 0 and len(self.error_msg) == 0 and len(self.error) > 1:
err = self.error.pop(-1)
raise err.exc(err.msg)
else:
if len(err.msg) == 0:
err.msg = self.error_msg
raise exc(self.error_msg)

# main entry point for Ast node evaluation
# parse: text of statements -> ast
Expand All @@ -266,6 +271,9 @@ def run(self, node, expr=None, lineno=None, with_raise=True):
"""Execute parsed Ast representation for an expression."""
# Note: keep the 'node is None' test: internal code here may run
# run(None) and expect a None in return.
if isinstance(node, str):
return self.eval(node, raise_errors=with_raise)

out = None
if len(self.error) > 0:
return out
Expand All @@ -275,8 +283,7 @@ def run(self, node, expr=None, lineno=None, with_raise=True):
return self._interrupt
if node is None:
return out
if isinstance(node, str):
node = self.parse(node)

if lineno is not None:
self.lineno = lineno
if expr is not None:
Expand Down Expand Up @@ -312,7 +319,8 @@ def _remove_duplicate_errors(self):
for err in self.error[1:]:
lerr = error[-1]
if err.exc != lerr.exc or err.expr != lerr.expr or err.msg != lerr.msg:
error.append(err)
if isinstance(err.msg, str) and len(err.msg) > 0:
error.append(err)
self.error = error

def __call__(self, expr, **kw):
Expand Down

0 comments on commit 8d7326d

Please sign in to comment.