import collections class keydefaultdict(collections.defaultdict): """Improved defaultdict to pass the requested key to factory function.""" def __missing__(self, key): print 'accessed keydefaultdict.__missing__(%s)' % key if self.default_factory is None: raise KeyError("Invalid key '{0}' and no default factory was set") else: val = self.default_factory(key) self[key] = val return val def foo(k): return k + k kdd = keydefaultdict(foo) # line below causes KeyError in Jython, ignoring overridden __missing__ method assert kdd[3] == 6 assert kdd['ab'] == 'abab'