Skip to content

Commit 198adec

Browse files
Gatsikjaraco
authored andcommitted
gh-121735: Fix inferring caller when resolving importlib.resources.files()
without anchor
1 parent 21afd61 commit 198adec

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

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'

importlib_resources/tests/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
@@ -122,6 +126,33 @@ def test_implicit_files_submodule(self):
122126
"""
123127
assert importlib.import_module('somepkg.submod').val == 'resources are the best'
124128

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

126157
class ImplicitContextFilesDiskTests(
127158
DirectSpec, util.DiskSetup, ImplicitContextFiles, unittest.TestCase

0 commit comments

Comments
 (0)