Skip to content
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
Comment on lines +191 to +192
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a fan of repeating ourselves. Now we have 6 lines of code where previous 1 was sufficient... and moreover, these lines of code are entangled (their comments both refer to the same motivation and should be kept in sync. Better would be to do:

Suggested change
# Deferred for performance.
import tempfile
tempfile = _import_tempfile()

And then in _import_tempfile, document the motivation, which should not only include the basic motivation ("deferred for performance"), but also details on what performance is saved. For example, it should link to the PR ("#328") and that PR should have examples of how much performance is saved.


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)
Comment on lines +195 to +196
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't care for this refactor. The reason _temp_path exists is to decouple the pathlib.Path construction from the invocation of the write function. Yes, it's logically the same, but without the presence of _temp_path the defect that tempfile doesn't provide pathlib objects is hidden. Let's keep _temp_path, especially as its presence isn't implicated in the purpose of this change.



def _write_contents(target, source):
Expand Down