weakrefs and bound methods

Mathias Panzenboeck e0427417 at student.tuwien.ac.at
Sun Oct 7 10:51:33 EDT 2007


Hi.

I have a problem with weak refs and bound methods. The best explanation for the
problem is a short bit of code. I have the three classes Wrapper, Foo and Bar:

import weakref

class Wrapper(object):
	def __init__(self,x):
		self.x = weakref.ref(x)

	def __call__(self,*args,**kwargs):
		x = self.x()
		if x is None:
			print "lost reference"
		else:
			return x(*args,**kwargs)

class Foo(object):
	def __init__(self):
		self._methods = set()
		self._methods.add(Wrapper(self._foo))

	def _foo(self):
		print "_foo"

	def callMethods(self):
		for method in self._methods:
			method()

	def __del__(self):
		print "del Foo"

class Bar(object):
	def __init__(self):
		self._methods = set()
		self._methods.add(self._foo)

	def _foo(self):
		print "_foo"

	def callMethods(self):
		for method in self._methods:
			method()

	def __del__(self):
		print "del Bar"



Now look what happens when I do this:

>>> f=Foo()
>>> f.callMethods()
lost reference
>>> del f
del Foo
>>> b=Bar()
>>> b.callMethods()
_foo
>>> del b
>>>

Foo looses the reference to its method but Bar on the other hand has a refloop and
never gets deleted.

Does anyone know what happens here? How can I write such classes without refloop and
without lost reference?

I'm using:
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2

	-panzi



More information about the Python-list mailing list