Skip to content

Commit

Permalink
pythongh-121735: Fix inferring caller when resolving importlib.resour…
Browse files Browse the repository at this point in the history
…ces.files()

without anchor
  • Loading branch information
Gatsik committed Aug 16, 2024
1 parent 35d8ac7 commit 50c1596
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
7 changes: 6 additions & 1 deletion Lib/importlib/resources/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
31 changes: 31 additions & 0 deletions Lib/test/test_importlib/resources/test_files.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import os
import pathlib
import py_compile
import shutil
import textwrap
import unittest
import warnings
Expand Down Expand Up @@ -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()

0 comments on commit 50c1596

Please sign in to comment.