bpo-38735: Don't fail when importing from / with sys.pycache_prefix set (GH-30456)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Petr Viktorin 2025-08-18 13:53:01 +02:00 committed by GitHub
parent 043f251154
commit d8a9466e29
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 16 additions and 1 deletions

View file

@ -297,7 +297,8 @@ def cache_from_source(path, debug_override=None, *, optimization=None):
# Strip initial drive from a Windows path. We know we have an absolute # Strip initial drive from a Windows path. We know we have an absolute
# path here, so the second part of the check rules out a POSIX path that # path here, so the second part of the check rules out a POSIX path that
# happens to contain a colon at the second character. # happens to contain a colon at the second character.
if head[1] == ':' and head[0] not in path_separators: # Slicing avoids issues with an empty (or short) `head`.
if head[1:2] == ':' and head[0:1] not in path_separators:
head = head[2:] head = head[2:]
# Strip initial path separator from `head` to complete the conversion # Strip initial path separator from `head` to complete the conversion

View file

@ -580,6 +580,18 @@ def test_cache_from_source_respects_pycache_prefix_relative(self):
self.util.cache_from_source(path, optimization=''), self.util.cache_from_source(path, optimization=''),
os.path.normpath(expect)) os.path.normpath(expect))
@unittest.skipIf(sys.implementation.cache_tag is None,
'requires sys.implementation.cache_tag to not be None')
def test_cache_from_source_in_root_with_pycache_prefix(self):
# Regression test for gh-82916
pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
path = 'qux.py'
expect = os.path.join(os.path.sep, 'tmp', 'bytecode',
f'qux.{self.tag}.pyc')
with util.temporary_pycache_prefix(pycache_prefix):
with os_helper.change_cwd('/'):
self.assertEqual(self.util.cache_from_source(path), expect)
@unittest.skipIf(sys.implementation.cache_tag is None, @unittest.skipIf(sys.implementation.cache_tag is None,
'requires sys.implementation.cache_tag to not be None') 'requires sys.implementation.cache_tag to not be None')
def test_source_from_cache_inside_pycache_prefix(self): def test_source_from_cache_inside_pycache_prefix(self):

View file

@ -0,0 +1,2 @@
Fix failure when importing a module from the root directory on unix-like
platforms with sys.pycache_prefix set.