Free Memory

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat May 10 23:46:18 EDT 2008


En Fri, 09 May 2008 12:44:21 -0300, Patrick Mullen <saluk64007 at gmail.com> escribió:

> I had some very interesting results with this code to do what is asked:
>
> for key in globals().keys():
>     del globals()[key]
> for key in locals().keys():
>     del locals()[key]

Removing items from locals() has no effect, at least on CPython. Local variables doesn't "live" on that dictionary, locals() is built on demand when required.
At module level, locals and globals are the same thing.

py> def foo():
...   x = 1
...   y = "hello"
...   print locals()
...   for key in locals().keys():
...     print "deleting", key
...     del locals()[key]
...   print locals()
...   print x, y
...
py> foo()
{'y': 'hello', 'x': 1}
deleting y
deleting x
{'y': 'hello', 'x': 1, 'key': 'x'}
1 hello

BTW, if you want to clear a dictionary, just use its clear() method. So a more compact form of your code would be: globals.clear().
Anyway I don't see why do you want to keep an empty module around - just remove it from sys.modules, and if nobody else holds a reference to it, it will be destroyed.

> It might be better to reverse the two steps, I didn't give it much thought.
> Anyway, when this is done, all of the builtins spill into globals and locals
> (since __builtin__ was deleted).  I thought that was interesting.

Sorry I don't understand you...

> It did have the effect that is asked for, although there may be more
> unintended consequences.  Also if any objects are attached to any of the
> builtins I expect they will still be around.

Your code removes all direct references to objects from the current module, it does not free memory "per se". There may be other references elsewhere. Objects are deleted (and memory freed) only when their reference count reaches zero.

-- 
Gabriel Genellina




More information about the Python-list mailing list