[issue20443] __code__. co_filename should always be an absolute path

STINNER Victor report at bugs.python.org
Fri Jun 14 07:13:33 EDT 2019


STINNER Victor <vstinner at redhat.com> added the comment:

The site module tries to compute the absolute path of __file__ and __cached__ attributes of all modules in sys.modules:

def abs_paths():
    """Set all module __file__ and __cached__ attributes to an absolute path"""
    for m in set(sys.modules.values()):
        if (getattr(getattr(m, '__loader__', None), '__module__', None) not in
                ('_frozen_importlib', '_frozen_importlib_external')):
            continue   # don't mess with a PEP 302-supplied __file__
        try:
            m.__file__ = os.path.abspath(m.__file__)
        except (AttributeError, OSError, TypeError):
            pass
        try:
            m.__cached__ = os.path.abspath(m.__cached__)
        except (AttributeError, OSError, TypeError):
            pass

The __path__ attribute isn't updated.

Another approach would be to hack importlib to compute the absolute path before loading a module, rather than trying to fix it *afterwards*.

One pratical problem: posixpath and ntpath are not available when importlib is setup, these modules are implemented in pure Python and so must be imported.

Maybe importlib could use a naive implementation of os.path.abspath(). Maybe the C function _Py_abspath() that I implemented in PR 14053 should be exposed somehow to importlib as a private function using a builtin module like _imp, so it can be used directly.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue20443>
_______________________________________


More information about the Python-bugs-list mailing list