[IPython-user] question about garbage collection
killian koepsell
koepsell@gmail....
Sun Jul 20 22:02:53 CDT 2008
I meant to post this to the list.
kilian
---------- Forwarded message ----------
Hi Fernando,
> There is in principle no automatic way of getting all object
> references in python. However, since most important variables you
> care about live in a dict called _ip.user_ns, you could write a bit of
> code to build the reverse mapping to find all the references bound to
> a given object in that namespace:
>
> refs = {}
> for k in _ip.user_ns.keys():
> refs.setdefault(id(_ip.user_ns[k]),[]).append(k)
that is very useful information and helped me to narrow down where the
extra reference to my object is coming from.
if i edit a simple script test.py that does nothing than creating an object:
class C(object):
def __del__(self):
print 'deleting object...'
c = C()
this object is afterwards in the namespace and it is also referenced by the
dictionary _ip.user_ns:
In [1]: edit test_destructor.py
Editing... done. Executing edited code...
In [2]: import gc
In [3]: refs = gc.get_referrers(c)
In [4]: map(id,refs)
Out[4]: [7607760]
In [5]: id (_ip.user_ns)
Out[5]: 7607760
the del command removes the only reference and the garbage is collected:
In [6]: del c
deleting object...
however, when i run the example script with the %run command, there seem
to be _two_ references created and del does not destroy the object.
In [7]: run test_destructor.py
In [8]: refs = gc.get_referrers(c)
In [9]: map(id,refs)
Out[9]: [7808896, 7607760]
In [10]: del c
i wasn't able to figure out what the name of the other object (7808896) is,
but it is another dictionary and if i remove the extra reference, my object
is deleted:
In [11]: type(refs[0])
Out[23]: <type 'dict'>
In [12]: refs[0].keys()
Out[24]: ['C', '__nonzero__', '__builtins__', '__file__', 'c']
In [13]: del refs[0]['c']
deleting object...
Do you know where this extra dictionary lives?
Is there a separate namespace created for each file that is run by the
%run command?
Thanks,
Kilian
More information about the IPython-user
mailing list