bug?: exception and references

Balazs Scheidler bazsi at balabit.hu
Mon Jan 15 09:10:03 EST 2001


Hi,

I have a problem with exceptions incrementing the reference counter of an
instance whose method is raising the exception. To illustrate the problem
here's an example completely written in Python:

We have two methods in RaiseTest, func1 raising an exception on error, and
func2 returning a -1 value. If an instance of this class is created, and the
function func1 is called, freeing up the instance is delayed. If func2 is
called everything works normally.

class RaiseTest:

	def __del__(self):
		print "__del__ called"

	def func1(self):
		raise NotImplementedError
		
	def func2(self):
		return -1

	

def test1():
	print "test1"
	
	r = RaiseTest()
	try:
		r.func1()
	except NotImplementedError:
		pass
	del r
	print "r deleted1"

def test2():
	print "test2"
	
	r = RaiseTest()
	r.func2()
	del r
	print "r deleted2"

test1()
test2()


Results of the script:

balabit:~/src$ python proba.py
test1
r deleted1
__del__ called
test2
__del__ called
r deleted2

The order of messages is important. In test1, the instance is deleted using
"del", but is not freed until the current frame exits (this time test1), in
test2, the instance is correctly freed when "del" is called.

Something thus holds a reference to the instance, even if it's deleted from
the local namespace of test1(), my question is what it might be? 

I'm using Python as an extension language, and I call the method using
PyObject_CallObject(), if an exception is raised in the function, nothing
frees up the object instance (because of the extra reference).

Any help is welcome.

PS: please CC me as I'm not on the list.

-- 
Bazsi
PGP info: KeyID 9AF8D0A9 Fingerprint CD27 CFB0 802C 0944 9CFD 804E C82C 8EB1
     url: http://www.balabit.hu/pgpkey.txt




More information about the Python-list mailing list