Skip to content

Commit

Permalink
feat: get cleaner stack trace
Browse files Browse the repository at this point in the history
  • Loading branch information
CNSeniorious000 committed Aug 18, 2024
1 parent 1be0600 commit df73491
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
24 changes: 21 additions & 3 deletions reasonify-headless/reasonify/utils/run.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from contextlib import redirect_stderr, redirect_stdout
from functools import cache
from io import StringIO
from itertools import count
from json import loads
from traceback import format_exception, format_exception_only
from traceback import format_exception, format_exception_only, walk_tb
from typing import Callable

from promplate import Context
Expand Down Expand Up @@ -30,7 +31,12 @@ def diff_context(context_in: Context, context_out: Context):
return {k: v for k, v in context_out.items() if not k.startswith("__") and (k not in context_in or is_different(context_in[k], v))}


counter = count(1).__next__


async def run(source: str):
filename = f"In[{counter()}]"

context = get_context()

original_context = context.copy()
Expand All @@ -43,9 +49,9 @@ async def run(source: str):

with redirect_stdout(io), redirect_stderr(io):
try:
result = await eval_code_async(source, context)
result = await eval_code_async(source, context, filename=filename)
except Exception as e:
io.write("\n".join(format_exception(e)))
io.write(get_clean_traceback(e, filename))

if diff := diff_context(original_context, context):
out["global values"] = diff
Expand All @@ -68,3 +74,15 @@ async def run(source: str):
def register[T: Callable](function: T) -> T:
get_context()[function.__name__] = function
return function


def get_clean_traceback(e: BaseException, filename: str):
keep_frames = False
n = 0
for frame, _ in walk_tb(e.__traceback__):
if keep_frames:
n += 1
elif frame.f_code.co_filename == filename:
keep_frames = True
n += 1
return "".join(format_exception(type(e), e, e.__traceback__, -n))
2 changes: 1 addition & 1 deletion reasonify-headless/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.1.1"
__version__ = "0.1.2"

0 comments on commit df73491

Please sign in to comment.