Skip to content

Commit c8311f6

Browse files
AlexWaygoodmiss-islington
authored andcommitted
gh-125519: Improve traceback if importlib.reload() is called with a non-module object (GH-125520)
(cherry picked from commit c5c21fe) Co-authored-by: Alex Waygood <[email protected]>
1 parent 9a22ec7 commit c8311f6

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

Lib/importlib/__init__.py

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

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

Lib/test/test_importlib/test_api.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import sys
99
from test.support import import_helper
1010
from test.support import os_helper
11+
import traceback
1112
import types
1213
import unittest
1314
import warnings
@@ -354,6 +355,20 @@ def test_module_missing_spec(self):
354355
with self.assertRaises(ModuleNotFoundError):
355356
self.init.reload(module)
356357

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+
357372

358373
(Frozen_ReloadTests,
359374
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)