How to properly override the default factory of defaultdict?

Chris Angelico rosuav at
Sun Feb 14 20:04:20 EST 2016

On Mon, Feb 15, 2016 at 11:17 AM, Herman <sorsorday at> wrote:
> I want to pass in the key to the default_factory of defaultdict and I found
> that defaultdict somehow can intercept my call to dict.__getitem__(self,
> key), so my class's __getitem__ have to catch a TypeError instead instead
> of KeyError. The following class is my code:

Save yourself a lot of trouble, and just override __missing__:

class DefaultDictWithEnhancedFactory(collections.defaultdict):
    def __missing__(self, key):
        return self.default_factory(key)


More information about the Python-list mailing list