Skip to content
Open
Next Next commit
Check bytecode before accepting a breakpoint in pdb
  • Loading branch information
aisk committed Feb 22, 2026
commit 7df087ee86f1d4dbd1ade3bf78499a4abc4723f1
20 changes: 20 additions & 0 deletions Lib/bdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,17 @@ def _get_lineno(self, code, offset):
return last_lineno


def _get_executable_linenos(code):
linenos = set()
for _, _, lineno in code.co_lines():
if lineno is not None:
linenos.add(lineno)
for const in code.co_consts:
if hasattr(const, 'co_lines'):
linenos |= _get_executable_linenos(const)
return linenos


class Bdb:
"""Generic Python debugger base class.

Expand Down Expand Up @@ -671,6 +682,15 @@ def set_break(self, filename, lineno, temporary=False, cond=None,
line = linecache.getline(filename, lineno)
if not line:
return 'Line %s:%d does not exist' % (filename, lineno)
source = ''.join(linecache.getlines(filename))
if source:
try:
code = compile(source, filename, 'exec')
executable_lines = _get_executable_linenos(code)
if executable_lines and lineno not in executable_lines:
return 'Line %d has no code associated with it' % lineno
except SyntaxError:
pass
self._add_to_breaks(filename, lineno)
bp = Breakpoint(filename, lineno, temporary, cond, funcname)
# After we set a new breakpoint, we need to search through all frames
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -4188,6 +4188,22 @@ def test_breakpoint(self):
self.assertTrue(any("Breakpoint 1 at" in l for l in stdout.splitlines()), stdout)
self.assertTrue(all("SUCCESS" not in l for l in stdout.splitlines()), stdout)

def test_breakpoint_on_no_bytecode_line(self):
script = """
x = 1
def f():
global x # line 4: no bytecode
x = 2
f()
"""
commands = """
b 4
c
quit
"""
stdout, _ = self.run_pdb_module(script, commands)
self.assertIn('no code', '\n'.join(stdout.splitlines()))

def test_run_pdb_with_pdb(self):
commands = """
c
Expand Down