Skip to content

Commit 84658bc

Browse files
committed
use files() api in is_resource()
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 <[email protected]>
1 parent 7d12fd6 commit 84658bc

File tree

3 files changed

+13
-17
lines changed

3 files changed

+13
-17
lines changed

importlib_resources/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@
88
read_binary,
99
open_text,
1010
read_text,
11+
is_resource,
1112
)
1213

1314
from importlib_resources._py3 import (
1415
Package,
1516
Resource,
16-
is_resource,
1717
path,
1818
)
1919
from importlib_resources.abc import ResourceReader

importlib_resources/_common.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,15 @@ def contents(package: Package) -> Iterable[str]:
166166
to check if it is a resource or not.
167167
"""
168168
return [path.name for path in files(package).iterdir()]
169+
170+
171+
def is_resource(package: Package, name: str) -> bool:
172+
"""True if `name` is a resource inside `package`.
173+
174+
Directories are *not* resources.
175+
"""
176+
resource = normalize_path(name)
177+
for traversable in files(package).iterdir():
178+
if traversable.name == resource:
179+
return traversable.is_file()
180+
return False

importlib_resources/_py3.py

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -54,22 +54,6 @@ def _path_from_open_resource(reader, resource):
5454
return _common._tempfile(saved.read, suffix=resource)
5555

5656

57-
def is_resource(package: Package, name: str) -> bool:
58-
"""True if `name` is a resource inside `package`.
59-
60-
Directories are *not* resources.
61-
"""
62-
package = _common.get_package(package)
63-
_common.normalize_path(name)
64-
reader = _common.get_resource_reader(package)
65-
if reader is not None:
66-
return reader.is_resource(name)
67-
package_contents = set(_common.contents(package))
68-
if name not in package_contents:
69-
return False
70-
return (_common.from_package(package) / name).is_file()
71-
72-
7357
@singledispatch
7458
def _ensure_sequence(iterable):
7559
return list(iterable)

0 commit comments

Comments
 (0)