Skip to content

Commit 7de5d02

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

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
@@ -567,7 +567,8 @@ def cache_from_source(path, debug_override=None, *, optimization=None):
567567
# Strip initial drive from a Windows path. We know we have an absolute
568568
# path here, so the second part of the check rules out a POSIX path that
569569
# happens to contain a colon at the second character.
570-
if head[1] == ':' and head[0] not in path_separators:
570+
# Slicing avoids issues with an empty (or short) `head`.
571+
if head[1:2] == ':' and head[0:1] not in path_separators:
571572
head = head[2:]
572573

573574
# 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
@@ -581,6 +581,18 @@ def test_cache_from_source_respects_pycache_prefix_relative(self):
581581
self.util.cache_from_source(path, optimization=''),
582582
os.path.normpath(expect))
583583

584+
@unittest.skipIf(sys.implementation.cache_tag is None,
585+
'requires sys.implementation.cache_tag to not be None')
586+
def test_cache_from_source_in_root_with_pycache_prefix(self):
587+
# Regression test for gh-82916
588+
pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
589+
path = 'qux.py'
590+
expect = os.path.join(os.path.sep, 'tmp', 'bytecode',
591+
f'qux.{self.tag}.pyc')
592+
with util.temporary_pycache_prefix(pycache_prefix):
593+
with os_helper.change_cwd('/'):
594+
self.assertEqual(self.util.cache_from_source(path), expect)
595+
584596
@unittest.skipIf(sys.implementation.cache_tag is None,
585597
'requires sys.implementation.cache_tag to not be None')
586598
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)