1
Vote

Breakpoint not working for module loaded using imp.load_module

description

Repro requires two modules, as follows:
# main.py
import imp
import module1
with open('module1.py', 'r') as f:
    module1 = imp.load_module('module1', f, "module1.py", (".py", "r", imp.PY_SOURCE))
module1.foo()
# module1.py
import sys
print(sys._getframe().f_code.co_filename)
def foo():
    print(sys._getframe().f_code.co_filename)
Then set a breakpoint in module1.py at print on line #1, and then another one on print inside foo().

To repro, launch main.py using "Start with Debugging" on the opened file outside of any project (this is crucial; if files are in an opened project, it will not repro). The first breakpoint - in global scope - is hit, but the one inside the function is not.

If 'import module1' line is removed from main.py, then we hit both breakpoints correctly.

The issue here is that when the module is loaded first time using import, its code object has an absolute file path (resolved by Python). That path matches the one specified in the breakpoint, and so we mark the breakpoint as bound - meaning that any future matches against that breakpoint require an exact path match. However, when we then load the same module with load_module(), this creates a new code object with a relative file path (as specified in the call; Python does not try to normalize it). When that module is run, all code objects in it have co_filename as a relative path as well, and so it doesn't match against the bound breakpoint anymore.

comments