Skip to content

Commit fa3933a

Browse files
committed
gh-130932: Fix incorrect exception handling in _PyModule_IsPossiblyShadowing
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 a025f27 commit fa3933a

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Lib/test/test_import/__init__.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,6 +1185,27 @@ class substr(str):
11851185
for line in lines:
11861186
self.assertRegex(line, rb"cannot import name 'Fraction' from 'fractions' \(.*\)")
11871187

1188+
def test_script_shadowing_stdlib_cwd_failure(self):
1189+
with os_helper.temp_dir() as tmp:
1190+
subtmp = os.path.join(tmp, "subtmp")
1191+
os.mkdir(subtmp)
1192+
with open(os.path.join(subtmp, "main.py"), "w", encoding='utf-8') as f:
1193+
f.write(f"""
1194+
import sys
1195+
assert sys.path[0] == ''
1196+
1197+
import os
1198+
import shutil
1199+
shutil.rmtree(os.getcwd())
1200+
1201+
os.does_not_exist
1202+
""")
1203+
# Use -c to ensure sys.path[0] is ""
1204+
popen = script_helper.spawn_python("-c", "import main", cwd=subtmp)
1205+
stdout, stderr = popen.communicate()
1206+
expected_error = rb"AttributeError: module 'os' has no attribute 'does_not_exist'"
1207+
self.assertRegex(stdout, expected_error)
1208+
11881209
def test_script_shadowing_stdlib_sys_path_modification(self):
11891210
script_errors = [
11901211
(

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)