clear memory? how?

Ben C spamspam at spam.eggs
Tue May 9 17:37:19 CEST 2006


On 2006-05-09, Diez B. Roggisch <deets at nospam.web.de> wrote:
> N/A wrote:
>
>> Hi all,
>> I am learning Python. Just wondering how to clear saved memory in
>> Python? Like in Matlab I can simply use "clear all" to clear all saved
>> memory.
>
> You don't - python does it for you. It is called garbage collection. All you
> have to to is get into granny-mode(tm): forget about things. That means:
> once an object is not referenced by your code anymore, it will be cleaned
> up.

I think Matlab's "clear all" is more like what you might call "del all"
in python.

You could perhaps define it like this:

def clearall():
    all = [var for var in globals() if var[0] != "_"]
    for var in all:
        del globals()[var]

This deletes any global not starting with an _, since it's probably
inadvisable to delete this lot:

{'__builtins__': <module '__builtin__' (built-in)>, '__file__':
'/etc/pythonstart', '__name__': '__main__', '__doc__': None}

More correct I suppose might be something like this:

def clearall():
    all = [var for var in globals() if "__" not in (var[:2], var[-2:])]
    for var in all:
        del globals()[var]

since I think magic things always start and end with __.

Looking briefly at GNU octave which is similar to MatLab, clear all may
also del all the locals; so you can do something similar with the
builtin function locals().



More information about the Python-list mailing list