diff --git a/CHANGELOG.md b/CHANGELOG.md index decc900b..87938824 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ Changelog follow https://keepachangelog.com/ format. ## [Unreleased] +* `epath`: + * Fix resource_path when used on a adhoc-imported module. + ## [1.5.1] - 2023-10-10 * `epath`: diff --git a/etils/epath/resource_utils.py b/etils/epath/resource_utils.py index 3ddd1c08..853315f4 100644 --- a/etils/epath/resource_utils.py +++ b/etils/epath/resource_utils.py @@ -109,18 +109,20 @@ def resource_path(package: Union[str, types.ModuleType]) -> abstract_path.Path: Returns: The read-only path to the root module directory """ - try: - path = importlib_resources.files(package) # pytype: disable=module-attr - except AttributeError as e: - # TODO(b/260333695): Adhoc import fail with adhoc imports - # Currently, hack around to add support for it + path = importlib_resources.files(package) # pytype: disable=module-attr + + # TODO(b/260333695): Adhoc import fail with adhoc imports + # When module are imported with adhoc, `importlib_resources.files` returns + # a non-path object, so convert manually. + if isinstance( + path, importlib_resources._adapters.CompatibilityFiles.SpecPath # pylint: disable=protected-access + ): # Note this is not the true path (`/google_src/` vs # `/export/.../server/ml_notebook.runfiles`), but should be equivalent. - if 'submodule_search_locations' not in str(e): - raise path = pathlib.Path(sys.modules[package].__file__) if path.name == '__init__.py': path = path.parent + if isinstance(path, pathlib.Path): # TODO(etils): To ensure compatibility with zipfile.Path, we should ensure # that the returned `pathlib.Path` isn't missused. More specifically: