Skip to content

gh-112414: Fix AttributeError when calling repr() on a namespace package imported with a custom loader #112425

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

Merged
merged 1 commit into from
Nov 27, 2023
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
10 changes: 8 additions & 2 deletions Lib/importlib/_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,10 +824,16 @@ def _module_repr_from_spec(spec):
"""Return the repr to use for the module."""
name = '?' if spec.name is None else spec.name
if spec.origin is None:
if spec.loader is None:
loader = spec.loader
if loader is None:
return f'<module {name!r}>'
elif (
_bootstrap_external is not None
and isinstance(loader, _bootstrap_external.NamespaceLoader)
):
return f'<module {name!r} (namespace) from {list(loader._path)}>'
else:
return f'<module {name!r} (namespace) from {list(spec.loader._path)}>'
return f'<module {name!r} ({loader!r})>'
else:
if spec.has_location:
return f'<module {name!r} from {spec.origin!r}>'
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_importlib/import_/test___loader__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ def test___loader__(self):
with util.uncache('blah'), util.import_state(meta_path=[loader]):
module = self.__import__('blah')
self.assertEqual(loader, module.__loader__)
expected_repr_pattern = (
r"<module 'blah' \(<test\.test_importlib\..*SpecLoaderMock object at .+>\)>"
)
self.assertRegex(repr(module), expected_repr_pattern)


(Frozen_SpecTests,
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_importlib/test_namespace_pkgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def test_cant_import_other(self):

def test_simple_repr(self):
import foo.one
assert repr(foo).startswith("<module 'foo' (namespace) from [")
self.assertTrue(repr(foo).startswith("<module 'foo' (namespace) from ["))


class DynamicPathNamespacePackage(NamespacePackageTest):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix regression in Python 3.12 where calling :func:`repr` on a module that
had been imported using a custom :term:`loader` could fail with
:exc:`AttributeError`. Patch by Alex Waygood.