Skip to content

Commit bac6e8e

Browse files
committed
Extract function for _is_present_dir.
1 parent 9afeb05 commit bac6e8e

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

importlib_resources/_common.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,18 +97,26 @@ def _temp_file(path):
9797
return _tempfile(path.read_bytes, suffix=path.name)
9898

9999

100+
def _is_present_dir(path: Traversable) -> bool:
101+
"""
102+
Some Traversables implement ``is_dir()`` to raise an
103+
exception (i.e. ``FileNotFoundError``) when the
104+
directory doesn't exist. This function wraps that call
105+
to always return a boolean and only return True
106+
if there's a dir and it exists.
107+
"""
108+
with contextlib.suppress(FileNotFoundError):
109+
return path.is_dir()
110+
return False
111+
112+
100113
@functools.singledispatch
101114
def as_file(path):
102115
"""
103116
Given a Traversable object, return that object as a
104117
path on the local file system in a context manager.
105118
"""
106-
try:
107-
is_dir = path.is_dir()
108-
except FileNotFoundError:
109-
is_dir = False
110-
111-
return _temp_dir(path) if is_dir else _temp_file(path)
119+
return _temp_dir(path) if _is_present_dir(path) else _temp_file(path)
112120

113121

114122
@as_file.register(pathlib.Path)

0 commit comments

Comments
 (0)