Skip to content

Commit ddd1264

Browse files
miss-islingtonencukouserhiy-storchaka
authored
[3.14] gh-82916: Don't fail when importing from / with sys.pycache_prefix set (GH-30456) (GH-137906)
(cherry picked from commit d8a9466) Co-authored-by: Petr Viktorin <[email protected]> Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 0accda7 commit ddd1264

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/importlib/_bootstrap_external.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,8 @@ def cache_from_source(path, debug_override=None, *, optimization=None):
297297
# Strip initial drive from a Windows path. We know we have an absolute
298298
# path here, so the second part of the check rules out a POSIX path that
299299
# happens to contain a colon at the second character.
300-
if head[1] == ':' and head[0] not in path_separators:
300+
# Slicing avoids issues with an empty (or short) `head`.
301+
if head[1:2] == ':' and head[0:1] not in path_separators:
301302
head = head[2:]
302303

303304
# Strip initial path separator from `head` to complete the conversion

Lib/test/test_importlib/test_util.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,18 @@ def test_cache_from_source_respects_pycache_prefix_relative(self):
580580
self.util.cache_from_source(path, optimization=''),
581581
os.path.normpath(expect))
582582

583+
@unittest.skipIf(sys.implementation.cache_tag is None,
584+
'requires sys.implementation.cache_tag to not be None')
585+
def test_cache_from_source_in_root_with_pycache_prefix(self):
586+
# Regression test for gh-82916
587+
pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
588+
path = 'qux.py'
589+
expect = os.path.join(os.path.sep, 'tmp', 'bytecode',
590+
f'qux.{self.tag}.pyc')
591+
with util.temporary_pycache_prefix(pycache_prefix):
592+
with os_helper.change_cwd('/'):
593+
self.assertEqual(self.util.cache_from_source(path), expect)
594+
583595
@unittest.skipIf(sys.implementation.cache_tag is None,
584596
'requires sys.implementation.cache_tag to not be None')
585597
def test_source_from_cache_inside_pycache_prefix(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix failure when importing a module from the root directory on unix-like
2+
platforms with sys.pycache_prefix set.

0 commit comments

Comments
 (0)