Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix epath.resource_path on Colab #458

Merged
merged 1 commit into from
Oct 25, 2023
Merged
Changes from all 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
26 changes: 18 additions & 8 deletions etils/epath/resource_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,20 +109,29 @@ def resource_path(package: Union[str, types.ModuleType]) -> abstract_path.Path:
Returns:
The read-only path to the root module directory
"""
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
):
try:
path = importlib_resources.files(package) # pytype: disable=module-attr
except AttributeError:
is_adhoc = True
else:
if isinstance(
path, importlib_resources._adapters.CompatibilityFiles.SpecPath # pylint: disable=protected-access
):
is_adhoc = True
else:
is_adhoc = False

if is_adhoc:
# TODO(b/260333695): `importlib_resources` fail with adhoc imports
# When module are imported with adhoc, `importlib_resources.files` returns
# a non-path object, so convert manually.
# Note this is not the true path (`/google_src/` vs
# `/export/.../server/ml_notebook.runfiles`), but should be equivalent.
path = pathlib.Path(sys.modules[package].__file__)
if path.name == '__init__.py':
path = path.parent

# pylint: disable=undefined-variable
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 All @@ -137,6 +146,7 @@ def resource_path(package: Union[str, types.ModuleType]) -> abstract_path.Path:
return typing.cast(abstract_path.Path, path)
else:
raise TypeError(f'Unknown resource path: {type(path)}: {path}')
# pylint: enable=undefined-variable


def to_write_path(path: abstract_path.Path) -> abstract_path.Path:
Expand Down
Loading