Can I reliably unimport a Python module if I import it in a namespace?
<p>Basically, I have a long running process where I would like to be able to unimport modules and recover memory via the gc. I've read about deleting modules <a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a> and it seems like there are still dangling references that block gc.</p>

<p>However, what if I import and use the module only inside a namespace. In other words, something like this:</p>

<pre><code>ns = {}
exec somecode in ns
</code></pre>

<p>Then I would cleanup sys.modules inside the namespace and finish off by deleting the namespace itself. </p>

<p>Would that free up the memory for reuse in CPython?</p>

<p>If not, then is it possible to access some part of the Python C API using ctypes, to accomplish this?</p>

<p>The important part of the end result is that memory is released so that a process running for weeks or months, can reliably unimport a module without reloading it. Of course it is entirely possible that any given module would be loaded and unloaded many times during that time period. I am assuming that a module could create a large number of objects while it is loaded, and that the normally cleanup (sys.modules and del) would leave those objects in memory forever.</p>

<p>Jochen: Yes, I could work around this in a number of ways but I am interested in exploring the limits of Python.</p>
