Python exceptions and refcounts

Bernhard Herzog bh at intevation.de
Tue Jan 22 08:28:26 EST 2002


Christian Weichenberger <x_beelze at hotmail.com> writes:

> --------------------------------------------
> import gc
> import sys;
> 
> def foo(d):
> 	print "Refcount in function:", sys.getrefcount(d);
> 	#del d
> 	raise RuntimeError
> 	
> dic = {"spam1": 100, "spam2": 200};
> print "Refcount after init:", sys.getrefcount(dic);
> 
> try:
> 	foo(dic);
> except RuntimeError:
> 	#sys.exc_traceback = None;
> 	pass ;
> 
> print "Refcount after error handling:", sys.getrefcount(dic);
> print "Unreachable objects: ", gc.collect();
> --------------------------------------------
> 
>  The first print is ok, the reference count is 2. In the function, the
> ref count is 4 which is the first thing that is not very
> understandable to me. Shouldn't it be 3 (1 for the init, 1 for the
> passing of the reference to the function and 1 for the sys.getrefcount
> function call)?

There's also a refcount for the local variable d.

> Anyway, after rasing and handling the exception the refcount then is
> 3. Ideally it should be 2, as it is when the offending raise statement
> is commented out.

The traceback holds references to the local variables including the
dictionary.

  Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                               http://mapit.de/



More information about the Python-list mailing list