Python exceptions and refcounts

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Jan 22 11:43:56 EST 2002


Christian Weichenberger <x_beelze at hotmail.com> wrote in 
news:3C4D6082.61DED5B8 at hotmail.com:

> 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 refcount drops back to 2 after the next time you throw an exception. 
Until another exception is thrown, the traceback from your exception keeps 
a reference to the function's local variables.

If you need to be sure that references to an object are removed even if the 
function throws an exception then wrap the body of the function in a 
try:finally: block and del the object in the finally suite. Also remember 
always to close things like files and not depend on the variable going out 
of scope to do the tidying up.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list