Skip to content

Commit 0a9ae5e

Browse files
authored
gh-130932: Fix incorrect exception handling in _PyModule_IsPossiblyShadowing (#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. ```
1 parent 8190571 commit 0a9ae5e

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
@@ -1185,6 +1185,28 @@ class substr(str):
11851185
for line in lines:
11861186
self.assertRegex(line, rb"cannot import name 'Fraction' from 'fractions' \(.*\)")
11871187

1188+
@unittest.skipIf(sys.platform == 'win32', 'Cannot delete cwd on Windows')
1189+
def test_script_shadowing_stdlib_cwd_failure(self):
1190+
with os_helper.temp_dir() as tmp:
1191+
subtmp = os.path.join(tmp, "subtmp")
1192+
os.mkdir(subtmp)
1193+
with open(os.path.join(subtmp, "main.py"), "w", encoding='utf-8') as f:
1194+
f.write(f"""
1195+
import sys
1196+
assert sys.path[0] == ''
1197+
1198+
import os
1199+
import shutil
1200+
shutil.rmtree(os.getcwd())
1201+
1202+
os.does_not_exist
1203+
""")
1204+
# Use -c to ensure sys.path[0] is ""
1205+
popen = script_helper.spawn_python("-c", "import main", cwd=subtmp)
1206+
stdout, stderr = popen.communicate()
1207+
expected_error = rb"AttributeError: module 'os' has no attribute 'does_not_exist'"
1208+
self.assertRegex(stdout, expected_error)
1209+
11881210
def test_script_shadowing_stdlib_sys_path_modification(self):
11891211
script_errors = [
11901212
(
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
@@ -921,7 +921,9 @@ _PyModule_IsPossiblyShadowing(PyObject *origin)
921921
if (sys_path_0[0] == L'\0') {
922922
// if sys.path[0] == "", treat it as if it were the current directory
923923
if (!_Py_wgetcwd(sys_path_0_buf, MAXPATHLEN)) {
924-
return -1;
924+
// If we failed to getcwd, don't raise an exception and instead
925+
// let the caller proceed assuming no shadowing
926+
return 0;
925927
}
926928
sys_path_0 = sys_path_0_buf;
927929
}

0 commit comments

Comments
 (0)