Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-125519: Improve traceback if importlib.reload() is called with a non-module object #125520

Merged
merged 1 commit into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/importlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_importlib/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from test import support
from test.support import import_helper
from test.support import os_helper
import traceback
import types
import unittest

Expand Down Expand Up @@ -354,6 +355,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)
Comment on lines +358 to +370
Copy link
Member Author

@AlexWaygood AlexWaygood Oct 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could also do this with assertions on the __cause__ or __context__ attribute of the raised exception, but that feels like asserting an implementation detail to me. I prefer for the test to assert what the user will be seeing when the exception is raised (which feels like the important thing).



(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.
Loading