Skip to content

Commit

Permalink
[3.12] gh-125519: Improve traceback if importlib.reload() is called…
Browse files Browse the repository at this point in the history
… 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]>
  • Loading branch information
miss-islington and AlexWaygood authored Oct 21, 2024
1 parent 9a22ec7 commit 8cc8d7d
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Lib/importlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def reload(module):
try:
name = module.__name__
except AttributeError:
raise TypeError("reload() argument must be a module")
raise TypeError("reload() argument must be a module") from None

if sys.modules.get(name) is not module:
raise ImportError(f"module {name} not in sys.modules", name=name)
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_importlib/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import sys
from test.support import import_helper
from test.support import os_helper
from test import support
import traceback
import types
import unittest
import warnings
Expand Down Expand Up @@ -354,6 +356,20 @@ def test_module_missing_spec(self):
with self.assertRaises(ModuleNotFoundError):
self.init.reload(module)

def test_reload_traceback_with_non_str(self):
# gh-125519
with support.captured_stdout() as stdout:
try:
self.init.reload("typing")
except TypeError as exc:
traceback.print_exception(exc, file=stdout)
else:
self.fail("Expected TypeError to be raised")
printed_traceback = stdout.getvalue()
self.assertIn("TypeError", printed_traceback)
self.assertNotIn("AttributeError", printed_traceback)
self.assertNotIn("module.__spec__.name", printed_traceback)


(Frozen_ReloadTests,
Source_ReloadTests
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve traceback if :func:`importlib.reload` is called with an object that
is not a module. Patch by Alex Waygood.

0 comments on commit 8cc8d7d

Please sign in to comment.