Skip to content

Defer tempfile import to sites of use #328

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 8 additions & 12 deletions importlib_resources/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import itertools
import os
import pathlib
import tempfile
import types
import warnings
from typing import Optional, Union, cast
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -180,24 +182,18 @@ 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):
"""
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 _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):
Expand Down