]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-125519: Improve traceback if `importlib.reload()` is called with a non...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 21 Oct 2024 08:28:32 +0000 (10:28 +0200)
committerGitHub <noreply@github.com>
Mon, 21 Oct 2024 08:28:32 +0000 (08:28 +0000)
gh-125519: Improve traceback if `importlib.reload()` is called with a non-module object (GH-125520)
(cherry picked from commit c5c21fee7ae1ea689a351caa454c98e716a6e537)

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Lib/importlib/__init__.py
Lib/test/test_importlib/test_api.py
Misc/NEWS.d/next/Library/2024-10-15-14-01-03.gh-issue-125519.TqGh6a.rst [new file with mode: 0644]

index f38fe5c1ab461acc794d19f0fdf91e9979b2d05c..a7d57561ead046c481d4d78bf33a6726185e399d 100644 (file)
@@ -103,7 +103,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)
index 2a35f3dcb7210c80c119fb06d797ddbf71784f50..3bf8d7ac9c4022f3b49f8c71ab03043c45b027e8 100644 (file)
@@ -8,6 +8,8 @@ import os.path
 import sys
 from test.support import import_helper
 from test.support import os_helper
+from test import support
+import traceback
 import types
 import unittest
 
@@ -353,6 +355,20 @@ class ReloadTests:
             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
diff --git a/Misc/NEWS.d/next/Library/2024-10-15-14-01-03.gh-issue-125519.TqGh6a.rst b/Misc/NEWS.d/next/Library/2024-10-15-14-01-03.gh-issue-125519.TqGh6a.rst
new file mode 100644 (file)
index 0000000..e606262
--- /dev/null
@@ -0,0 +1,2 @@
+Improve traceback if :func:`importlib.reload` is called with an object that
+is not a module. Patch by Alex Waygood.