Skip to content

Commit 196b092

Browse files
committed
only clear a module's __dict__ if the module is the only one with a reference to it python#7140
1 parent 96e319e commit 196b092

3 files changed

Lines changed: 15 additions & 1 deletion

File tree

Lib/test/test_module.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ def test_reinit(self):
5555
{"__name__": "foo", "__doc__": "foodoc", "bar": 42})
5656
self.assertTrue(foo.__dict__ is d)
5757

58+
def test_dont_clear_dict(self):
59+
# See issue 7140.
60+
def f():
61+
foo = ModuleType("foo")
62+
foo.bar = 4
63+
return foo
64+
self.assertEqual(f().__dict__["bar"], 4)
65+
5866
def test_main():
5967
run_unittest(ModuleTests)
6068

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ What's New in Python 2.7 alpha 1
1212
Core and Builtins
1313
-----------------
1414

15+
- Issue #7140: The __dict__ of a module should not be cleared unless the module
16+
is the only object holding a reference to it.
17+
1518
- Issue #1754094: Improve the stack depth calculation in the compiler.
1619
There should be no other effect than a small decrease in memory use.
1720
Patch by Christopher Tur Lesniewski-Laas.

Objects/moduleobject.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,10 @@ module_dealloc(PyModuleObject *m)
175175
{
176176
PyObject_GC_UnTrack(m);
177177
if (m->md_dict != NULL) {
178-
_PyModule_Clear((PyObject *)m);
178+
/* If we are the only ones holding a reference, we can clear
179+
the dictionary. */
180+
if (Py_REFCNT(m->md_dict) == 1)
181+
_PyModule_Clear((PyObject *)m);
179182
Py_DECREF(m->md_dict);
180183
}
181184
Py_TYPE(m)->tp_free((PyObject *)m);

0 commit comments

Comments
 (0)