How to properly override the default factory of defaultdict?

Herman sorsorday at gmail.com
Thu Feb 18 12:41:33 EST 2016


d = dictutil.DefaultDictWithEnhancedFactory(lambda k: k)
        self.assertEqual("apple", d['apple'])

From: Ben Finney <ben+python at benfinney.id.au>
>
> you are using the inheritance hierarchy but thwarting it by not using
> ‘super’. Instead::
>
>     super().__init__(self, default_factory, *a, **kw)
>
> and::
>
>     super().__getitem__(self, key)
> --
>  \       "Those who will not reason, are bigots, those who cannot, are |
>   `\        fools, and those who dare not, are slaves." —“Lord” George |
> _o__)                                                Gordon Noel Byron |
> Ben Finney

super does not work for defaultdict. I am using python 2.7. If I use
super(defaultdict, self).__init__(default_factory, *a, **kw), I get the
error:

    super(defaultdict, self).__init__(default_factory, *a, **kw)
TypeError: 'function' object is not iterable

My use case is:
d = dictutil.DefaultDictWithEnhancedFactory(lambda k: k)
        self.assertEqual("apple", d['apple'])


> From: Chris Angelico <rosuav at gmail.com>
>
> Save yourself a lot of trouble, and just override __missing__:
>
> class DefaultDictWithEnhancedFactory(collections.defaultdict):
>     def __missing__(self, key):
>         return self.default_factory(key)
>
> ChrisA
>
This works! Thanks.

From: "Steven D'Aprano" <steve+comp.lang.python at pearwood.info>
> > 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
>
Look like inheriting from defaultdict is easier. I don't even  have to
override the constructor as suggested by Chris Angelico above. Thanks.



More information about the Python-list mailing list