How to properly override the default factory of defaultdict?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 14 22:56:32 EST 2016


On Monday 15 February 2016 11:17, Herman wrote:

> I want to pass in the key to the default_factory of defaultdict 

Just use a regular dict and define __missing__:

class MyDefaultDict(dict):
    def __missing__(self, key):
        return "We gotcha key %r right here!" % key


If you want a per-instance __missing__, do something like this:


class MyDefaultDict(dict):
    def __init__(self, factory):
        self._factory = factory
    def __missing__(self, key):
        return self._factory(self, key)


d = MyDefaultDict(lambda self, key: ...)


-- 
Steve



More information about the Python-list mailing list