diff --git a/Lib/inspect.py b/Lib/inspect.py index f0b72662a9a0b2..db37cee6d04234 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -909,6 +909,9 @@ def getfile(object): if ismodule(object): if getattr(object, '__file__', None): return object.__file__ + if getattr(object, '__path__', None): + # Implicit namespace package. See PEP 420. + return object.__path__[0] raise TypeError('{!r} is a built-in module'.format(object)) if isclass(object): if hasattr(object, '__module__'): diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py index 09d50859970c99..f014ad57f8ada9 100644 --- a/Lib/test/test_inspect/test_inspect.py +++ b/Lib/test/test_inspect/test_inspect.py @@ -740,6 +740,10 @@ def __repr__(self): with self.assertRaises(TypeError): inspect.getfile(er) + def test_getfile_implicit_namespace_package(self): + import test.test_importlib.namespace_pkgs.not_a_namespace_pkg as pkg + self.assertEqual(inspect.getfile(pkg), pkg.__path__[0]) + def test_getmodule_recursion(self): from types import ModuleType name = '__inspect_dummy' diff --git a/Misc/NEWS.d/next/Library/2022-05-11-17-53-59.gh-issue-92525.YkK50p.rst b/Misc/NEWS.d/next/Library/2022-05-11-17-53-59.gh-issue-92525.YkK50p.rst new file mode 100644 index 00000000000000..b13f87ed816d15 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-05-11-17-53-59.gh-issue-92525.YkK50p.rst @@ -0,0 +1 @@ +Make ``inspect.getfile`` understand PEP 420 implicit namespace packages