@@ -630,29 +630,32 @@ def format(self, *, chain=True):
630
630
The message indicating which exception occurred is always the last
631
631
string in the output.
632
632
"""
633
- def queue_entry_for_exc (exc ):
634
- context = exc .__context__ if not exc .__suppress_context__ else None
635
- return [exc .__cause__ , context , exc .stack , exc ]
636
-
637
- queue = [queue_entry_for_exc (self )]
638
- while queue :
639
- next = queue .pop ()
640
- if isinstance (next , str ):
641
- yield next
633
+
634
+ stack = []
635
+ exc = self
636
+ while exc :
637
+ if chain :
638
+ if exc .__cause__ :
639
+ chained_msg = _cause_message
640
+ chained_exc = exc .__cause__
641
+ elif exc .__context__ and not exc .__suppress_context__ :
642
+ chained_msg = _context_message
643
+ chained_exc = exc .__context__
644
+ else :
645
+ chained_msg = None
646
+ chained_exc = None
647
+
648
+ stack .append ((chained_msg , exc ))
649
+ exc = chained_exc
642
650
else :
643
- cause , context , stack , exc = next
644
- if chain :
645
- if cause is not None :
646
- queue .append ([None , context , stack , exc ])
647
- queue .append (_cause_message )
648
- queue .append (queue_entry_for_exc (cause ))
649
- continue
650
- elif context is not None :
651
- queue .append ([None , None , stack , exc ])
652
- queue .append (_context_message )
653
- queue .append (queue_entry_for_exc (context ))
654
- continue
655
- if stack :
656
- yield 'Traceback (most recent call last):\n '
657
- yield from stack .format ()
658
- yield from exc .format_exception_only ()
651
+ stack .append ((None , exc ))
652
+ exc = None
653
+
654
+ while stack :
655
+ msg , exc = stack .pop ()
656
+ if msg is not None :
657
+ yield msg
658
+ if exc .stack :
659
+ yield 'Traceback (most recent call last):\n '
660
+ yield from exc .stack .format ()
661
+ yield from exc .format_exception_only ()
0 commit comments