Skip to content

Commit 2fb5f03

Browse files
authored
bpo-40924: Ensure importlib.resources.path returns an extant path (GH-20857)
1 parent e67f7db commit 2fb5f03

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

Lib/importlib/readers.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,19 @@ class FileReader(abc.TraversableResources):
77
def __init__(self, loader):
88
self.path = pathlib.Path(loader.path).parent
99

10+
def resource_path(self, resource):
11+
"""
12+
Return the file system path to prevent
13+
`resources.path()` from creating a temporary
14+
copy.
15+
"""
16+
return str(self.path.joinpath(resource))
17+
1018
def files(self):
1119
return self.path
1220

1321

14-
class ZipReader(FileReader):
22+
class ZipReader(abc.TraversableResources):
1523
def __init__(self, loader, module):
1624
_, _, name = module.rpartition('.')
1725
prefix = loader.prefix.replace('\\', '/') + name + '/'
@@ -28,3 +36,6 @@ def is_resource(self, path):
2836
# for non-existent paths.
2937
target = self.files().joinpath(path)
3038
return target.is_file() and target.exists()
39+
40+
def files(self):
41+
return self.path

Lib/test/test_importlib/test_path.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@ def test_reading(self):
2727
class PathDiskTests(PathTests, unittest.TestCase):
2828
data = data01
2929

30+
def test_natural_path(self):
31+
"""
32+
Guarantee the internal implementation detail that
33+
file-system-backed resources do not get the tempdir
34+
treatment.
35+
"""
36+
with resources.path(self.data, 'utf-8.file') as path:
37+
assert 'data' in str(path)
38+
3039

3140
class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
3241
def test_remove_in_context_manager(self):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Ensure ``importlib.resources.path`` returns an extant path for the
2+
SourceFileLoader's resource reader. Avoids the regression identified in
3+
master while a long-term solution is devised.

0 commit comments

Comments
 (0)