Skip to content

inspect.getfile doesn't properly handle PEP 420 #92525

Open

Description

@TheTechRobo

Bug report

inspect.getfile handles all __file__ is None modules as built-in. Cf.

cpython/Lib/inspect.py

Lines 898 to 901 in f298ba1

if ismodule(object):
if getattr(object, '__file__', None):
return object.__file__
raise TypeError('{!r} is a built-in module'.format(object))

This leads to PEP 420 packages being treated as built-in, as implicit namespaces have file set to None, but __path__ set to the actual path.

Creating PEP 420 directory:

~ ❯❯❯ mkdir python_test
~ ❯❯❯ vim python_test/hello.py

Python interpreter

Python 3.9.7 (default, Oct 10 2021, 14:08:54)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import python_test
>>> import inspect
>>> inspect.getfile(python_test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/python-3.9.7/lib/python3.9/inspect.py", line 660, in getfile
    raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module 'python_test' (namespace)> is a built-in module
>>> print(python_test.__file__)
None
>>> print(python_test.__path__)
_NamespacePath(['/home/thetechrobo/python_test'])

Your environment

  • CPython versions tested on: 3.9.7
  • Operating system and architecture: Elive Linux 3.8.27 64-bit (Debian Bullseye); custom Python installation

Apologies if this is a duplicate. I've searched for any related issues, but I may have missed one.

Linked PRs

Activity

  1. added a commit that references this issue on May 21, 2022
  2. added 3 commits that reference this issue on Aug 31, 2022
  3. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 23, 2023
  4. serhiy-storchaka commented on Dec 15, 2023

    @serhiy-storchaka
    Member

    What are you going to do with the result? You cannot open a file, and inspect.getsource() will still fail.

  5. TheTechRobo commented on Dec 15, 2023

    @TheTechRobo
    Author

    @serhiy-storchaka I tried to use it for debugging, trying to figure out where the package was being imported from. The error message is currently wrong so it is a pretty annoying issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions