Skip to content

Commit 7cb935e

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 7adc99b commit 7cb935e

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
@@ -164,3 +164,15 @@ def contents(package: Package) -> Iterable[str]:
164164
to check if it is a resource or not.
165165
"""
166166
return [path.name for path in files(package).iterdir()]
167+
168+
169+
def is_resource(package: Package, name: str) -> bool:
170+
"""True if `name` is a resource inside `package`.
171+
172+
Directories are *not* resources.
173+
"""
174+
resource = normalize_path(name)
175+
for traversable in files(package).iterdir():
176+
if traversable.name == resource:
177+
return traversable.is_file()
178+
return False

importlib_resources/_py3.py

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

5353

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

0 commit comments

Comments
 (0)