Skip to content

Commit 9c10fc8

Browse files
committed
Python: Remove workerd runtime frames from the top of stack trace
Python tracebacks include some frames that are not related to user code but are in the workerd runtime. This trims them off.
1 parent c052767 commit 9c10fc8

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/pyodide/internal/introspection.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import sys
12
from inspect import isawaitable, isclass
3+
from traceback import TracebackException
24
from types import FunctionType
35

46
import js
@@ -86,3 +88,20 @@ async def wrapper_func(relaxed, inst, prop, *args, **kwargs):
8688
return python_to_rpc(await result)
8789
else:
8890
return python_to_rpc(result)
91+
92+
93+
def excepthook(_type, exc, _tb):
94+
"""Remove workerd runtime frames from the top of the stack trace."""
95+
tb_exc = TracebackException.from_exception(exc)
96+
for idx, frame in enumerate(tb_exc.stack):
97+
fn = frame.filename
98+
# We're trying to remove frames named "introspection.py" and
99+
# "/lib/python313.zip/pyodide/code.py".
100+
if fn.startswith("/") and not fn.startswith("/lib/python313.zip/pyodide/"):
101+
first_user_frame = idx
102+
break
103+
del tb_exc.stack[:first_user_frame]
104+
tb_exc.print()
105+
106+
107+
sys.excepthook = excepthook

0 commit comments

Comments
 (0)