From a2c72fd65b79f70901be54a526a08ba098ce03a8 Mon Sep 17 00:00:00 2001 From: Sachaa-Thanasius <111999343+Sachaa-Thanasius@users.noreply.github.com> Date: Sun, 6 Apr 2025 20:03:58 -0400 Subject: [PATCH 1/2] Remove lone usage of tempfile at global scope to avoid needing it at import time. --- importlib_resources/_common.py | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/importlib_resources/_common.py b/importlib_resources/_common.py index 5f41c26..6f72d28 100644 --- a/importlib_resources/_common.py +++ b/importlib_resources/_common.py @@ -180,15 +180,6 @@ def _(path): yield path -@contextlib.contextmanager -def _temp_path(dir: tempfile.TemporaryDirectory): - """ - Wrap tempfile.TemporaryDirectory to return a pathlib object. - """ - with dir as result: - yield pathlib.Path(result) - - @contextlib.contextmanager def _temp_dir(path): """ @@ -196,8 +187,8 @@ def _temp_dir(path): to the file system in a context manager. """ assert path.is_dir() - with _temp_path(tempfile.TemporaryDirectory()) as temp_dir: - yield _write_contents(temp_dir, path) + with tempfile.TemporaryDirectory() as temp_dir: + yield _write_contents(pathlib.Path(temp_dir), path) def _write_contents(target, source): From 7135e5d9a8bc03ad438701d5268cf5595c942662 Mon Sep 17 00:00:00 2001 From: Sachaa-Thanasius <111999343+Sachaa-Thanasius@users.noreply.github.com> Date: Sun, 6 Apr 2025 20:06:53 -0400 Subject: [PATCH 2/2] Defer import of tempfile to within functions where it is used. --- importlib_resources/_common.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/importlib_resources/_common.py b/importlib_resources/_common.py index 6f72d28..d825219 100644 --- a/importlib_resources/_common.py +++ b/importlib_resources/_common.py @@ -5,7 +5,6 @@ import itertools import os import pathlib -import tempfile import types import warnings from typing import Optional, Union, cast @@ -127,6 +126,9 @@ def _tempfile( *, _os_remove=os.remove, ): + # Deferred for performance. + import tempfile + # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try' # blocks due to the need to close the temporary file to work on Windows # properly. @@ -186,6 +188,9 @@ def _temp_dir(path): Given a traversable dir, recursively replicate the whole tree to the file system in a context manager. """ + # Deferred for performance. + import tempfile + assert path.is_dir() with tempfile.TemporaryDirectory() as temp_dir: yield _write_contents(pathlib.Path(temp_dir), path)