[IPython-user] question about garbage collection
Fernando Perez
fperez.net@gmail....
Sun Jul 13 02:48:37 CDT 2008
Hey Kilian,
On Sun, Jul 13, 2008 at 12:08 AM, killian koepsell <koepsell@gmail.com> wrote:
> Hi,
>
> I noted the following behavior in ipython: If you run the following
> few lines in ipython, an object is created and destroyed:
>
> In [1]: class C(object):
> ...: def __del__(self):
> ...: print 'deleting object...'
> ...:
> ...:
>
> In [2]: obj = C()
>
> In [3]: del obj
> deleting object...
>
> The same, of course, works if you run theses line within a script that
> is called from ipython. If you don't delete the
> object at the end of the script, it is available afterwards in
> ipython. For some reason, the object destructor doesn't
> seem to be called when the object is later deleted. It seems that even
> after deleting the object, there is still some
> reference to that object around somewhere. Is this the expected/wanted
> behavior? Is it possible to force a complete
> destruction of the object in order to free the used memory?
If your object isn't getting deleted, likely it's because there are
other references to it:
In [4]: class C(object):
...: def __del__(self):
...: print 'deleting'
...:
In [5]: c=C()
This works OK:
In [6]: del c
deleting
But in this case:
In [7]: c=C()
If we have another reference:
In [8]: b=c
Deleting c doesn't do the trick:
In [9]: del c
It only goes away after we also delete b:
In [10]: del b
deleting
Note that in IPython, references are held to objects in lots of places:
In [23]: class C(object):
def __del__(self):
print 'deleting'
....:
....:
In [26]: c=C()
In [27]: c
Out[27]: <__main__.C object at 0x862262c>
In [28]: %reset
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
The deletion hasn't happened yet!
We have to try harder:
In [30]: del _27
In [31]: del Out[27]
In [32]: del ___
In [33]: import gc
In [34]: gc.collect()
Out[34]: 92
deleting
Finally!
So, in addition to using %reset and gc.collect(), I'd encourage you to
file a ticket for us to make %reset more robust. It really needs to
go deeper in cleanup mode.
Finally, you must keep in mind that __del__ methods aren't guaranteed
to be called, even absent ipython quirks. See
http://docs.python.org/ref/customization.html
for details.
cheers,
f
More information about the IPython-user
mailing list