Skip to content

gh-92525: make inspect.getfile PEP 420 compliant #92635

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__'):
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_inspect/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make ``inspect.getfile`` understand PEP 420 implicit namespace packages