Skip to content

Commit 863154c

Browse files
authored
bpo-31299: make it possible to filter out frames from tracebacks (GH-28067)
1 parent 22fe0eb commit 863154c

File tree

4 files changed

+34
-1
lines changed

4 files changed

+34
-1
lines changed

Doc/library/traceback.rst

+2-1
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,8 @@ capture data for later printing in a lightweight fashion.
357357

358358
Returns a string for printing one of the frames involved in the stack.
359359
This method gets called for each frame object to be printed in the
360-
:class:`StackSummary`.
360+
:class:`StackSummary`. If it returns ``None``, the frame is omitted
361+
from the output.
361362

362363
.. versionadded:: 3.11
363364

Lib/test/test_traceback.py

+28
Original file line numberDiff line numberDiff line change
@@ -1514,6 +1514,34 @@ def some_inner():
15141514
s.format(),
15151515
[f'{__file__}:{some_inner.__code__.co_firstlineno + 1}'])
15161516

1517+
def test_dropping_frames(self):
1518+
def f():
1519+
1/0
1520+
1521+
def g():
1522+
try:
1523+
f()
1524+
except:
1525+
return sys.exc_info()
1526+
1527+
exc_info = g()
1528+
1529+
class Skip_G(traceback.StackSummary):
1530+
def format_frame(self, frame):
1531+
if frame.name == 'g':
1532+
return None
1533+
return super().format_frame(frame)
1534+
1535+
stack = Skip_G.extract(
1536+
traceback.walk_tb(exc_info[2])).format()
1537+
1538+
self.assertEqual(len(stack), 1)
1539+
lno = f.__code__.co_firstlineno + 1
1540+
self.assertEqual(
1541+
stack[0],
1542+
f' File "{__file__}", line {lno}, in f\n 1/0\n'
1543+
)
1544+
15171545

15181546
class TestTracebackException(unittest.TestCase):
15191547

Lib/traceback.py

+3
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,9 @@ def format(self):
515515
last_name = None
516516
count = 0
517517
for frame in self:
518+
formatted_frame = self.format_frame(frame)
519+
if formatted_frame is None:
520+
continue
518521
if (last_file is None or last_file != frame.filename or
519522
last_line is None or last_line != frame.lineno or
520523
last_name is None or last_name != frame.name):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add option to completely drop frames from a traceback by returning ``None`` from a :meth:`~traceback.StackSummary.format_frame` override.

0 commit comments

Comments
 (0)