From 818e58d99e32efe8fe8ddf6d514e800c07f02407 Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Fri, 27 Oct 2017 12:11:24 -0700 Subject: [PATCH] Optimize opening a file when it already exists on disk --- importlib_resources/__init__.py | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/importlib_resources/__init__.py b/importlib_resources/__init__.py index eb81db01..da4e5f3e 100644 --- a/importlib_resources/__init__.py +++ b/importlib_resources/__init__.py @@ -46,20 +46,24 @@ def open(package: Package, file_name: FileName) -> BinaryIO: """Return a file-like object opened for binary-reading of the resource.""" file_name = _normalize_path(file_name) package = _get_package(package) - package_path = os.path.dirname(os.path.abspath(package.__spec__.origin)) - full_path = os.path.join(package_path, file_name) - # Just assume the loader is a resource loader; all the relevant - # importlib.machinery loaders are and an AttributeError for get_data() will - # make it clear what is needed from the loader. - loader = typing.cast(importlib.abc.ResourceLoader, package.__spec__.loader) - try: - data = loader.get_data(full_path) - except OSError: - package_name = package.__spec__.name - message = f'{file_name!r} resource not found in {package_name!r}' - raise FileNotFoundError(message) + package_path = pathlib.Path(package.__spec__.origin).resolve().parent + full_path = package_path / file_name + if full_path.exists(): + return full_path.open('rb') else: - return io.BytesIO(data) + # Just assume the loader is a resource loader; all the relevant + # importlib.machinery loaders are and an AttributeError for get_data() + # will make it clear what is needed from the loader. + loader = typing.cast(importlib.abc.ResourceLoader, + package.__spec__.loader) + try: + data = loader.get_data(str(full_path)) + except OSError: + package_name = package.__spec__.name + message = f'{file_name!r} resource not found in {package_name!r}' + raise FileNotFoundError(message) + else: + return io.BytesIO(data) def read(package: Package, file_name: FileName, encoding: str = 'utf-8',