Skip to content

Commit d5eb490

Browse files
[3.13] gh-130932: Fix incorrect exception handling in _PyModule_IsPossiblyShadowing (GH-130934) (#130939)
gh-130932: Fix incorrect exception handling in _PyModule_IsPossiblyShadowing (GH-130934) I chose to not raise an exception here because I think it would be confusing for module attribute access to start raising something other than AttributeError if e.g. the cwd goes away Without the change in moduleobject.c ``` ./python.exe -m unittest test.test_import.ImportTests.test_script_shadowing_stdlib_cwd_failure ... Assertion failed: (PyErr_Occurred()), function _PyObject_SetAttributeErrorContext, file object.c, line 1253. ``` (cherry picked from commit 0a9ae5e) Co-authored-by: Shantanu <[email protected]>
1 parent 0c088e4 commit d5eb490

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

Lib/test/test_import/__init__.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1203,6 +1203,28 @@ class substr(str):
12031203
for line in lines:
12041204
self.assertRegex(line, rb"cannot import name 'Fraction' from 'fractions' \(.*\)")
12051205

1206+
@unittest.skipIf(sys.platform == 'win32', 'Cannot delete cwd on Windows')
1207+
def test_script_shadowing_stdlib_cwd_failure(self):
1208+
with os_helper.temp_dir() as tmp:
1209+
subtmp = os.path.join(tmp, "subtmp")
1210+
os.mkdir(subtmp)
1211+
with open(os.path.join(subtmp, "main.py"), "w", encoding='utf-8') as f:
1212+
f.write(f"""
1213+
import sys
1214+
assert sys.path[0] == ''
1215+
1216+
import os
1217+
import shutil
1218+
shutil.rmtree(os.getcwd())
1219+
1220+
os.does_not_exist
1221+
""")
1222+
# Use -c to ensure sys.path[0] is ""
1223+
popen = script_helper.spawn_python("-c", "import main", cwd=subtmp)
1224+
stdout, stderr = popen.communicate()
1225+
expected_error = rb"AttributeError: module 'os' has no attribute 'does_not_exist'"
1226+
self.assertRegex(stdout, expected_error)
1227+
12061228
def test_script_shadowing_stdlib_sys_path_modification(self):
12071229
script_errors = [
12081230
(
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix incorrect exception handling in ``_PyModule_IsPossiblyShadowing``

Objects/moduleobject.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -908,7 +908,9 @@ _PyModule_IsPossiblyShadowing(PyObject *origin)
908908
if (sys_path_0[0] == L'\0') {
909909
// if sys.path[0] == "", treat it as if it were the current directory
910910
if (!_Py_wgetcwd(sys_path_0_buf, MAXPATHLEN)) {
911-
return -1;
911+
// If we failed to getcwd, don't raise an exception and instead
912+
// let the caller proceed assuming no shadowing
913+
return 0;
912914
}
913915
sys_path_0 = sys_path_0_buf;
914916
}

0 commit comments

Comments
 (0)