Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion importlib_resources/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,19 @@ def _(cand: None) -> types.ModuleType:
return resolve(_infer_caller().f_globals['__name__'])


@functools.lru_cache
def _this_filename():
frame = inspect.currentframe()
return __file__ if frame is None else inspect.getframeinfo(frame).filename


def _infer_caller():
"""
Walk the stack and find the frame of the first caller not in this module.
"""

def is_this_file(frame_info):
return frame_info.filename == __file__
return frame_info.filename == _this_filename()

def is_wrapper(frame_info):
return frame_info.function == 'wrapper'
Expand Down
30 changes: 30 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 All @@ -7,6 +11,7 @@
import importlib_resources as resources
from ..abc import Traversable
from . import util
from .compat.py39 import os_helper, import_helper


@contextlib.contextmanager
Expand Down Expand Up @@ -108,6 +113,10 @@ class ImplicitContextFiles:
'submod.py': set_val,
'res.txt': 'resources are the best',
},
'frozenpkg': {
'__init__.py': set_val.replace('importlib_resources', 'c_resources'),
'res.txt': 'resources are the best',
},
}

def test_implicit_files_package(self):
Expand All @@ -122,6 +131,27 @@ def test_implicit_files_submodule(self):
"""
assert importlib.import_module('somepkg.submod').val == 'resources are the best'

def _compile_importlib(self):
"""
Make a compiled-only copy of the importlib resources package.
"""
bin_site = self.fixtures.enter_context(os_helper.temp_dir())
c_resources = pathlib.Path(bin_site, 'c_resources')
sources = pathlib.Path(resources.__file__).parent
shutil.copytree(sources, c_resources, ignore=lambda *_: ['__pycache__'])

for dirpath, _, filenames in os.walk(c_resources):
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)
self.fixtures.enter_context(import_helper.DirsOnSysPath(bin_site))

def test_implicit_files_with_compiled_importlib(self):
self._compile_importlib()
assert importlib.import_module('frozenpkg').val == 'resources are the best'


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