Skip to content

Commit

Permalink
use files() api in is_resource()
Browse files Browse the repository at this point in the history
The files() api makes the identification of resources blury. Here we
re-implement is_resource() by mirroring the previous logic to the best
extent we can. This is not fully correct, as the files() api is not
fully compatible with the legacy api, but it is pretty close and as
correct as we can get. The semantics for what constitutes resources have
always been blurry in the first place.

Signed-off-by: Filipe Laíns <lains@riseup.net>
  • Loading branch information
FFY00 committed May 29, 2021
1 parent 25b47c3 commit a1b319c
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 17 deletions.
2 changes: 1 addition & 1 deletion importlib_resources/__init__.py
Expand Up @@ -8,12 +8,12 @@
read_binary,
open_text,
read_text,
is_resource,
)

from importlib_resources._py3 import (
Package,
Resource,
is_resource,
path,
)
from importlib_resources.abc import ResourceReader
Expand Down
12 changes: 12 additions & 0 deletions importlib_resources/_common.py
Expand Up @@ -165,3 +165,15 @@ def contents(package: Package) -> Iterable[str]:
to check if it is a resource or not.
"""
return [path.name for path in files(package).iterdir()]


def is_resource(package: Package, name: str) -> bool:
"""True if `name` is a resource inside `package`.
Directories are *not* resources.
"""
resource = normalize_path(name)
for traversable in files(package).iterdir():
if traversable.name == resource:
return traversable.is_file()
return False
16 changes: 0 additions & 16 deletions importlib_resources/_py3.py
Expand Up @@ -51,22 +51,6 @@ def _path_from_open_resource(reader, resource):
return _common._tempfile(saved.read, suffix=resource)


def is_resource(package: Package, name: str) -> bool:
"""True if `name` is a resource inside `package`.
Directories are *not* resources.
"""
package = _common.get_package(package)
_common.normalize_path(name)
reader = _common.get_resource_reader(package)
if reader is not None:
return reader.is_resource(name)
package_contents = set(_common.contents(package))
if name not in package_contents:
return False
return (_common.from_package(package) / name).is_file()


@singledispatch
def _ensure_sequence(iterable):
return list(iterable)
Expand Down

0 comments on commit a1b319c

Please sign in to comment.