Skip to content

Commit 1cc5c94

Browse files
bpo-42482: remove reference to exc_traceback from TracebackException (GH-23531)
(cherry picked from commit 427613f) Co-authored-by: Irit Katriel <[email protected]>
1 parent f4389bf commit 1cc5c94

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

Lib/test/test_traceback.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,6 +1083,18 @@ def test_context(self):
10831083
self.assertEqual(exc_info[0], exc.exc_type)
10841084
self.assertEqual(str(exc_info[1]), str(exc))
10851085

1086+
def test_no_refs_to_exception_and_traceback_objects(self):
1087+
try:
1088+
1/0
1089+
except Exception:
1090+
exc_info = sys.exc_info()
1091+
1092+
refcnt1 = sys.getrefcount(exc_info[1])
1093+
refcnt2 = sys.getrefcount(exc_info[2])
1094+
exc = traceback.TracebackException(*exc_info)
1095+
self.assertEqual(sys.getrefcount(exc_info[1]), refcnt1)
1096+
self.assertEqual(sys.getrefcount(exc_info[2]), refcnt2)
1097+
10861098
def test_comparison_basic(self):
10871099
try:
10881100
1/0
@@ -1133,6 +1145,16 @@ def raise_with_locals():
11331145
exc7 = traceback.TracebackException(*exc_info, limit=-2, capture_locals=True)
11341146
self.assertNotEqual(exc6, exc7)
11351147

1148+
def test_comparison_equivalent_exceptions_are_equal(self):
1149+
excs = []
1150+
for _ in range(2):
1151+
try:
1152+
1/0
1153+
except:
1154+
excs.append(traceback.TracebackException(*sys.exc_info()))
1155+
self.assertEqual(excs[0], excs[1])
1156+
self.assertEqual(list(excs[0].format()), list(excs[1].format()))
1157+
11361158
def test_unhashable(self):
11371159
class UnhashableException(Exception):
11381160
def __eq__(self, other):

Lib/traceback.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,6 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
500500
_seen=_seen)
501501
else:
502502
context = None
503-
self.exc_traceback = exc_traceback
504503
self.__cause__ = cause
505504
self.__context__ = context
506505
self.__suppress_context__ = \
@@ -608,7 +607,7 @@ def format(self, *, chain=True):
608607
not self.__suppress_context__):
609608
yield from self.__context__.format(chain=chain)
610609
yield _context_message
611-
if self.exc_traceback is not None:
610+
if self.stack:
612611
yield 'Traceback (most recent call last):\n'
613-
yield from self.stack.format()
612+
yield from self.stack.format()
614613
yield from self.format_exception_only()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:class:`~traceback.TracebackException` no longer holds a reference to the exception's traceback object. Consequently, instances of TracebackException for equivalent but non-equal exceptions now compare as equal.

0 commit comments

Comments
 (0)