diff --git a/Lib/importlib/resources/_common.py b/Lib/importlib/resources/_common.py index ca5b06743b46a6..f7a2affda89f7b 100644 --- a/Lib/importlib/resources/_common.py +++ b/Lib/importlib/resources/_common.py @@ -91,9 +91,14 @@ def _infer_caller(): """ Walk the stack and find the frame of the first caller not in this module. """ + this_frame = inspect.currentframe() + if this_frame is None: + this_file = __file__ + else: + this_file = inspect.getframeinfo(this_frame).filename def is_this_file(frame_info): - return frame_info.filename == __file__ + return frame_info.filename == this_file def is_wrapper(frame_info): return frame_info.function == 'wrapper' diff --git a/Lib/test/test_importlib/resources/test_files.py b/Lib/test/test_importlib/resources/test_files.py index 7df6d03ead7480..61012a64603ecc 100644 --- a/Lib/test/test_importlib/resources/test_files.py +++ b/Lib/test/test_importlib/resources/test_files.py @@ -1,3 +1,7 @@ +import os +import pathlib +import py_compile +import shutil import textwrap import unittest import warnings @@ -112,6 +116,33 @@ def test_implicit_files(self): _path.build(spec, self.site_dir) assert importlib.import_module('somepkg').val == 'resources are the best' + def _compile_importlib(self, target_dir): + importlib_dir = pathlib.Path(importlib.__file__).parent + shutil.copytree(importlib_dir, target_dir, ignore=lambda *_: ['__pycache__']) + + for dirpath, _, filenames in os.walk(target_dir): + for filename in filenames: + source_path = pathlib.Path(dirpath) / filename + cfile = source_path.with_suffix('.pyc') + py_compile.compile(source_path, cfile) + pathlib.Path.unlink(source_path) + + def test_implicit_files_with_compiled_importlib(self): + self._compile_importlib(pathlib.Path(self.site_dir) / 'cimportlib') + spec = { + 'somepkg': { + '__init__.py': textwrap.dedent( + """ + import cimportlib.resources as res + val = res.files().joinpath('res.txt').read_text(encoding='utf-8') + """ + ), + 'res.txt': 'resources are the best', + }, + } + _path.build(spec, self.site_dir) + assert importlib.import_module('somepkg').val == 'resources are the best' + if __name__ == '__main__': unittest.main()