Skip to content

Commit

Permalink
gh-121735: Fix inferring caller when resolving importlib.resources.fi…
Browse files Browse the repository at this point in the history
…les()

without anchor
  • Loading branch information
Gatsik authored and jaraco committed Aug 17, 2024
1 parent 21afd61 commit 198adec
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
7 changes: 6 additions & 1 deletion 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 importlib_resources/tests/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 @@ -122,6 +126,33 @@ def test_implicit_files_submodule(self):
"""
assert importlib.import_module('somepkg.submod').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'


class ImplicitContextFilesDiskTests(
DirectSpec, util.DiskSetup, ImplicitContextFiles, unittest.TestCase
Expand Down

0 comments on commit 198adec

Please sign in to comment.