Skip to content

Commit 6b31b2d

Browse files
[3.13] pythongh-125519: Improve traceback if importlib.reload() is called with a non-module object (pythonGH-125520) (python#125768)
pythongh-125519: Improve traceback if `importlib.reload()` is called with a non-module object (pythonGH-125520) (cherry picked from commit c5c21fe) Co-authored-by: Alex Waygood <[email protected]>
1 parent 73bd5bd commit 6b31b2d

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/importlib/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def reload(module):
103103
try:
104104
name = module.__name__
105105
except AttributeError:
106-
raise TypeError("reload() argument must be a module")
106+
raise TypeError("reload() argument must be a module") from None
107107

108108
if sys.modules.get(name) is not module:
109109
raise ImportError(f"module {name} not in sys.modules", name=name)

Lib/test/test_importlib/test_api.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import sys
99
from test.support import import_helper
1010
from test.support import os_helper
11+
from test import support
12+
import traceback
1113
import types
1214
import unittest
1315

@@ -353,6 +355,20 @@ def test_module_missing_spec(self):
353355
with self.assertRaises(ModuleNotFoundError):
354356
self.init.reload(module)
355357

358+
def test_reload_traceback_with_non_str(self):
359+
# gh-125519
360+
with support.captured_stdout() as stdout:
361+
try:
362+
self.init.reload("typing")
363+
except TypeError as exc:
364+
traceback.print_exception(exc, file=stdout)
365+
else:
366+
self.fail("Expected TypeError to be raised")
367+
printed_traceback = stdout.getvalue()
368+
self.assertIn("TypeError", printed_traceback)
369+
self.assertNotIn("AttributeError", printed_traceback)
370+
self.assertNotIn("module.__spec__.name", printed_traceback)
371+
356372

357373
(Frozen_ReloadTests,
358374
Source_ReloadTests
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve traceback if :func:`importlib.reload` is called with an object that
2+
is not a module. Patch by Alex Waygood.

0 commit comments

Comments
 (0)