Skip to content

Commit 50c1596

Browse files
committed
pythongh-121735: Fix inferring caller when resolving importlib.resources.files()
without anchor
1 parent 35d8ac7 commit 50c1596

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Lib/importlib/resources/_common.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,14 @@ def _infer_caller():
9191
"""
9292
Walk the stack and find the frame of the first caller not in this module.
9393
"""
94+
this_frame = inspect.currentframe()
95+
if this_frame is None:
96+
this_file = __file__
97+
else:
98+
this_file = inspect.getframeinfo(this_frame).filename
9499

95100
def is_this_file(frame_info):
96-
return frame_info.filename == __file__
101+
return frame_info.filename == this_file
97102

98103
def is_wrapper(frame_info):
99104
return frame_info.function == 'wrapper'

Lib/test/test_importlib/resources/test_files.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import os
2+
import pathlib
3+
import py_compile
4+
import shutil
15
import textwrap
26
import unittest
37
import warnings
@@ -112,6 +116,33 @@ def test_implicit_files(self):
112116
_path.build(spec, self.site_dir)
113117
assert importlib.import_module('somepkg').val == 'resources are the best'
114118

119+
def _compile_importlib(self, target_dir):
120+
importlib_dir = pathlib.Path(importlib.__file__).parent
121+
shutil.copytree(importlib_dir, target_dir, ignore=lambda *_: ['__pycache__'])
122+
123+
for dirpath, _, filenames in os.walk(target_dir):
124+
for filename in filenames:
125+
source_path = pathlib.Path(dirpath) / filename
126+
cfile = source_path.with_suffix('.pyc')
127+
py_compile.compile(source_path, cfile)
128+
pathlib.Path.unlink(source_path)
129+
130+
def test_implicit_files_with_compiled_importlib(self):
131+
self._compile_importlib(pathlib.Path(self.site_dir) / 'cimportlib')
132+
spec = {
133+
'somepkg': {
134+
'__init__.py': textwrap.dedent(
135+
"""
136+
import cimportlib.resources as res
137+
val = res.files().joinpath('res.txt').read_text(encoding='utf-8')
138+
"""
139+
),
140+
'res.txt': 'resources are the best',
141+
},
142+
}
143+
_path.build(spec, self.site_dir)
144+
assert importlib.import_module('somepkg').val == 'resources are the best'
145+
115146

116147
if __name__ == '__main__':
117148
unittest.main()

0 commit comments

Comments
 (0)