From 979870a6eeaf28347ea85b7e51403c22a101b626 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Filipe=20La=C3=ADns?= Date: Thu, 20 May 2021 19:39:51 +0100 Subject: [PATCH] use files() api in is_resource() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- importlib_resources/__init__.py | 2 +- importlib_resources/_common.py | 12 ++++++++++++ importlib_resources/_py3.py | 16 ---------------- 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/importlib_resources/__init__.py b/importlib_resources/__init__.py index b8d609f..fcb31b3 100644 --- a/importlib_resources/__init__.py +++ b/importlib_resources/__init__.py @@ -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 diff --git a/importlib_resources/_common.py b/importlib_resources/_common.py index 838a993..5e7da81 100644 --- a/importlib_resources/_common.py +++ b/importlib_resources/_common.py @@ -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 diff --git a/importlib_resources/_py3.py b/importlib_resources/_py3.py index 43dce10..3a791fc 100644 --- a/importlib_resources/_py3.py +++ b/importlib_resources/_py3.py @@ -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)