Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Lib/importlib/_bootstrap_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
# path here, so the second part of the check rules out a POSIX path that
# 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:]

# Strip initial path separator from `head` to complete the conversion
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_importlib/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,18 @@ def test_cache_from_source_respects_pycache_prefix_relative(self):
self.util.cache_from_source(path, optimization=''),
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,
'requires sys.implementation.cache_tag to not be None')
def test_source_from_cache_inside_pycache_prefix(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix failure when importing a module from the root directory on unix-like
platforms with sys.pycache_prefix set.
Loading