[issue40050] importlib: module.__spec__ leaks importlib namespaces (test_importlib leaked xxx references)

STINNER Victor report at bugs.python.org
Tue Mar 24 09:58:13 EDT 2020


STINNER Victor <vstinner at python.org> added the comment:

Quick & dirty workaround:

diff --git a/Lib/importlib/_bootstrap_external.py b/Lib/importlib/_bootstrap_external.py
index 7353bf9a78..d988552f2d 100644
--- a/Lib/importlib/_bootstrap_external.py
+++ b/Lib/importlib/_bootstrap_external.py
@@ -1620,7 +1620,10 @@ def _setup(_bootstrap_module):
     setattr(self_module, '_thread', thread_module)
 
     # Directly load the _weakref module (needed during bootstrap).
-    weakref_module = _bootstrap._builtin_from_name('_weakref')
+    if '_weakref' not in sys.modules:
+        weakref_module = _bootstrap._builtin_from_name('_weakref')
+    else:
+        weakref_module = sys.modules['_weakref']
     setattr(self_module, '_weakref', weakref_module)
 
     # Directly load the winreg module (needed during bootstrap).


But I think that the issue is larger than just _weakref.

* Maybe the test_importlib should before save/restore the the "Python state" rather than modifying modules
* Maybe module.__spec__ should leak less importlib internals: explicitly clear namespaces? Use static methods? I'm not sure how to do that.
* Remove module.__spec__? ... that would mean rejecting PEP 451 implemented in Python 3.4, that sounds like a major regression :-(

----------
nosy: +brett.cannon, eric.snow, ncoghlan
title: test_importlib leaked [6303, 6299, 6303] references -> importlib: module.__spec__ leaks  importlib namespaces (test_importlib leaked xxx references)

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40050>
_______________________________________


More information about the Python-bugs-list mailing list