Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f48f11c

Browse files
committed
SF Patch #441791, with changes: when "import foo.bar" fails with an
exception in the execution of bar, ensure that foo.bar exists. (Previously, while sys.modules['foo.bar'] would exist, foo.bar would only be created upon successful execution of bar. This is inconvenient; some would say wrong. :-)
1 parent fa712ca commit f48f11c

1 file changed

Lines changed: 16 additions & 4 deletions

File tree

Python/import.c

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,7 +1789,7 @@ static PyObject *
17891789
import_submodule(PyObject *mod, char *subname, char *fullname)
17901790
{
17911791
PyObject *modules = PyImport_GetModuleDict();
1792-
PyObject *m;
1792+
PyObject *m, *res = NULL;
17931793

17941794
/* Require:
17951795
if mod == None: subname == fullname
@@ -1829,9 +1829,21 @@ import_submodule(PyObject *mod, char *subname, char *fullname)
18291829
m = load_module(fullname, fp, buf, fdp->type);
18301830
if (fp)
18311831
fclose(fp);
1832-
if (m != NULL && mod != Py_None) {
1833-
if (PyObject_SetAttrString(mod, subname, m) < 0) {
1834-
Py_DECREF(m);
1832+
if (mod != Py_None) {
1833+
/* Irrespective of the success of this load, make a
1834+
reference to it in the parent package module.
1835+
A copy gets saved in the modules dictionary
1836+
under the full name, so get a reference from
1837+
there, if need be. (The exception is when
1838+
the load failed with a SyntaxError -- then
1839+
there's no trace in sys.modules. In that case,
1840+
of course, do nothing extra.) */
1841+
res = m;
1842+
if (res == NULL)
1843+
res = PyDict_GetItemString(modules, fullname);
1844+
if (res != NULL &&
1845+
PyObject_SetAttrString(mod, subname, res) < 0) {
1846+
Py_XDECREF(m);
18351847
m = NULL;
18361848
}
18371849
}

0 commit comments

Comments
 (0)