diff --git a/Lib/dis.py b/Lib/dis.py index 58c7f6419032c6..af5657860e5922 100644 --- a/Lib/dis.py +++ b/Lib/dis.py @@ -142,11 +142,16 @@ def distb(tb=None, *, file=None, show_caches=False, adaptive=False, show_offsets if tb is None: try: if hasattr(sys, 'last_exc'): - tb = sys.last_exc.__traceback__ + exc = sys.last_exc + tb = exc.__traceback__ + if isinstance(exc, SyntaxError): + raise RuntimeError("can't disassemble a SyntaxError") else: tb = sys.last_traceback except AttributeError: raise RuntimeError("no last traceback to disassemble") from None + + while tb.tb_next: tb = tb.tb_next disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file, show_caches=show_caches, adaptive=adaptive, show_offsets=show_offsets, show_positions=show_positions) diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py index f8bbcd35ca7c09..c44f3e6a4c9e6b 100644 --- a/Lib/test/test_dis.py +++ b/Lib/test/test_dis.py @@ -2478,6 +2478,16 @@ def test_distb_empty(self): with self.assertRaises(RuntimeError): dis.distb() + def test_distb_syntax_error(self): + try: + compile("???", "", "exec") + except SyntaxError as e: + sys.last_exc = e + sys.last_exc.__traceback__ = None + + with self.assertRaises(RuntimeError): + dis.distb() + def test_distb_last_traceback(self): self.maxDiff = None # We need to have an existing last traceback in `sys`: