Skip to content

Commit

Permalink
Fix resource_path when used on a adhoc-imported module.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 575848930
  • Loading branch information
Conchylicultor authored and The etils Authors committed Oct 23, 2023
1 parent 269f963 commit 3cf4317
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down
16 changes: 9 additions & 7 deletions etils/epath/resource_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 3cf4317

Please sign in to comment.