Skip to content

Commit 38bfa84

Browse files
mariocj89ncoghlan
authored andcommitted
bpo-32691: Use mod_spec.parent when running modules with pdb (pythonGH-5474)
Previously the module name was used, which broke relative imports when pdb was run against a plain module or submodule.
1 parent 4e9da0d commit 38bfa84

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

Lib/pdb.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1532,7 +1532,7 @@ def _runmodule(self, module_name):
15321532
__main__.__dict__.update({
15331533
"__name__": "__main__",
15341534
"__file__": self.mainpyfile,
1535-
"__package__": module_name,
1535+
"__package__": mod_spec.parent,
15361536
"__loader__": mod_spec.loader,
15371537
"__spec__": mod_spec,
15381538
"__builtins__": __builtins__,

Lib/test/test_pdb.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1447,10 +1447,41 @@ def test_relative_imports(self):
14471447
quit
14481448
"""
14491449
stdout, _ = self._run_pdb(['-m', self.module_name], commands)
1450-
self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()))
1450+
self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
14511451
self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
14521452
self.assertTrue(any("second var" in l for l in stdout.splitlines()))
14531453

1454+
def test_relative_imports_on_plain_module(self):
1455+
# Validates running a plain module. See bpo32691
1456+
self.module_name = 't_main'
1457+
support.rmtree(self.module_name)
1458+
main_file = self.module_name + '/runme.py'
1459+
init_file = self.module_name + '/__init__.py'
1460+
module_file = self.module_name + '/module.py'
1461+
self.addCleanup(support.rmtree, self.module_name)
1462+
os.mkdir(self.module_name)
1463+
with open(init_file, 'w') as f:
1464+
f.write(textwrap.dedent("""
1465+
top_var = "VAR from top"
1466+
"""))
1467+
with open(main_file, 'w') as f:
1468+
f.write(textwrap.dedent("""
1469+
from . import module
1470+
pass # We'll stop here and print the vars
1471+
"""))
1472+
with open(module_file, 'w') as f:
1473+
f.write(textwrap.dedent("""
1474+
var = "VAR from module"
1475+
"""))
1476+
commands = """
1477+
b 3
1478+
c
1479+
p module.var
1480+
quit
1481+
"""
1482+
stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
1483+
self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
1484+
14541485

14551486
def load_tests(*args):
14561487
from test import test_pdb
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Use mod_spec.parent when running modules with pdb

0 commit comments

Comments
 (0)