Skip to content

Commit

Permalink
related fixes to suppress repeated exceptions: see GH#132 and #129
Browse files Browse the repository at this point in the history
  • Loading branch information
newville committed Sep 7, 2024
1 parent 2085502 commit 9e4c20c
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions asteval/asteval.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,13 +222,11 @@ def raise_exception(self, node, exc=None, msg='', expr=None,
"""Add an exception."""
if self.error is None:
self.error = []
if len(self.error) > 1:
return
if expr is None:
expr = self.expr
if len(self.error) > 0 and not isinstance(node, ast.Module):
msg = f'{msg!s}'
msg = str(msg)
err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)

self._interrupt = ast.Raise()
self.error.append(err)
if self.error_msg is None:
Expand All @@ -237,7 +235,7 @@ def raise_exception(self, node, exc=None, msg='', expr=None,
self.error_msg = f"{exc:s}: {msg}"
if exc is None:
try:
exc = self.error[0].exc
exc = self.error[-1].exc
except:
exc = RuntimeError
raise exc(self.error_msg)
Expand Down Expand Up @@ -290,7 +288,6 @@ def run(self, node, expr=None, lineno=None, with_raise=True):

# run the handler: this will likely generate
# recursive calls into this run method.

try:
ret = handler(node)
if isinstance(ret, enumerate):
Expand All @@ -300,6 +297,15 @@ def run(self, node, expr=None, lineno=None, with_raise=True):
if with_raise:
self.raise_exception(node, expr=expr)
raise

# avoid too many repeated error messages (yes, this needs to be "2")
if len(self.error) > 2:
error = [self.error[0]]
for err in self.error[1:]:
le = error[-1]
if err.exc != le.exc or err.expr != le.expr or err.msg != le.msg:
error.append(err)
self.error = error
return None

def __call__(self, expr, **kw):
Expand All @@ -317,10 +323,10 @@ def eval(self, expr, lineno=0, show_errors=True, raise_errors=False):
except Exception:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = self.error[0].get_error()[1]
errmsg = self.error[-1].get_error()[1]
if raise_errors:
try:
exc = self.error[0].exc
exc = self.error[-1].exc
except Exception:
exc = RuntimeError
raise exc(errmsg)
Expand All @@ -334,10 +340,10 @@ def eval(self, expr, lineno=0, show_errors=True, raise_errors=False):
except:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = self.error[0].get_error()[1]
errmsg = self.error[-1].get_error()[1]
if raise_errors:
try:
exc = self.error[0].exc
exc = self.error[-1].exc
except Exception:
exc = RuntimeError
raise exc(errmsg)
Expand Down

0 comments on commit 9e4c20c

Please sign in to comment.