Python exceptions and refcounts

Christian Weichenberger x_beelze at hotmail.com
Tue Jan 22 07:52:18 EST 2002


 Dear Pythoneers,

by inspecting the reference count mechanism, I have detected that
raising 
exceptions in functions will not decrease the reference count when the
error
is passed to the outside. See the following lines of code:

--------------------------------------------
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)? 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.

 When explicitly deleting the variable before raising the exception,
things 
are ok again. This, however is a quite nasty solution.

 I have searched the Python newsgroup archive and there were two
interesting 
threads: One is called '__del__, exceptions and reference counting: an
evil 
trio' from 1997 but did not provide a solution. Another is called
'Please
Help with Unwanted Refcount' from 1996 and refers to the C API. There,
the
solution was to delete the traceback object sys.exc_traceback. Does not
help
on the Python level. 

 Interestingly, the Python garbage collector does not find any
unresolvable 
objects.

 Concerning this question, has there been any progress lately or is
there a
clean solution? 

 Thanks a lot for any help!!

   _Chris



More information about the Python-list mailing list