Skip to content

Commit 8cc8d7d

Browse files
[3.12] gh-125519: Improve traceback if importlib.reload() is called with a non-module object (GH-125520) (#125769)
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 8cc8d7d

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
@@ -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: 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
import warnings
@@ -354,6 +356,20 @@ def test_module_missing_spec(self):
354356
with self.assertRaises(ModuleNotFoundError):
355357
self.init.reload(module)
356358

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

358374
(Frozen_ReloadTests,
359375
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)