From 9aaf28c341e472f3b03defc8e063a036746b2419 Mon Sep 17 00:00:00 2001 From: Carl Bordum Hansen Date: Tue, 10 May 2022 20:41:05 +0200 Subject: [PATCH 1/2] gh-92525: make inspect.getfile PEP 420 compliant --- Lib/inspect.py | 3 +++ Lib/test/test_inspect.py | 5 +++++ .../Library/2022-05-11-17-53-59.gh-issue-92525.YkK50p.rst | 1 + 3 files changed, 9 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2022-05-11-17-53-59.gh-issue-92525.YkK50p.rst diff --git a/Lib/inspect.py b/Lib/inspect.py index 498ee7ab9eaf8a..444f2e9c85d731 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -898,6 +898,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.py b/Lib/test/test_inspect.py index be9f29e04ae110..6be0243ada4d94 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -634,6 +634,11 @@ def __repr__(self): with self.assertRaises(TypeError): inspect.getfile(er) + def test_getfile_implicit_namespace_package(self): + import test.test_importlib.namespace_pkgs.module_and_namespace_package as pkg + path = inspect.getfile(pkg) + self.assertNotIn("built-in", path) + 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 From b36238b68b9028c4a1ed5f5cb7a1eed7c49b5776 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Fri, 15 Dec 2023 15:53:52 +0200 Subject: [PATCH 2/2] Make test more strict. --- Lib/test/test_inspect/test_inspect.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py index 0d234ef0cf9e9a..f014ad57f8ada9 100644 --- a/Lib/test/test_inspect/test_inspect.py +++ b/Lib/test/test_inspect/test_inspect.py @@ -741,9 +741,8 @@ def __repr__(self): inspect.getfile(er) def test_getfile_implicit_namespace_package(self): - import test.test_importlib.namespace_pkgs.module_and_namespace_package as pkg - path = inspect.getfile(pkg) - self.assertNotIn("built-in", path) + 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