WeakrefValueDictionary of Callables?

Lloyd Weehuizen lfw at fusion.net.nz
Sun May 21 05:02:22 CEST 2006


I'm trying to set up a WeakrefValueDictionary of callables however as 
soon as my method that adds the callable to the dictionary exits the 
value is removed? Is there any way around this?

import weakref

class TestBinder:
	def __init__( self ):
		self.entries = weakref.WeakValueDictionary()
	def BindFunction( self, event_id, function ):
		self.entries[event_id] = function

	def CallFunction( self, event_id, *args ):
		self.entries[event_id]( *args )

class TestCase:
	def __init__( self, binder ):
		binder.BindFunction( TEST_EVENT, self.TestFunction )
	def TestFunction():
		print "TestFunction OK"

test_binder = TestBinder()
test_case = TestCase( test_binder )

test_binder.CallFunction( TEST_EVENT )

This generates a KeyError: 1, if I don't use weakrefs, then the TestCase 
object is never cleaned up until TestBinder is destroyed.


More information about the Python-list mailing list