How to properly override the default factory of defaultdict?

Ben Finney ben+python at
Sun Feb 14 19:36:45 EST 2016

Herman <sorsorday at> writes:

> 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:

I don't see an example of using that code, so that we can use it the
same way you are.

So I'll comment on some things that may not be relevant but nevertheless
should be addressed:

> class DefaultDictWithEnhancedFactory(defaultdict):
>     """Just like the standard python collections.dict,
>     but the default_factory takes the missing key as argument.

Your doc string should have only a brief (about 50–60 characters) single
line synopsis. If it's longer, you may be writing something too complex.
(See PEP 257.)

>     Args:

The class itself doesn't take arguments; its numerous methods do. I
think you mean these descriptions to be in the ‘__init__’ method's doc

>     def __init__(self, default_factory, *a, **kw):
>         defaultdict.__init__(self, default_factory, *a, **kw)
>     def __getitem__(self, key):
>         try:
>             return dict.__getitem__(self, key)

you are using the inheritance hierarchy but thwarting it by not using
‘super’. Instead::

    super().__init__(self, default_factory, *a, **kw)


    super().__getitem__(self, key)

If you're not using Python 3 (and you should, for new code), ‘super’ is
a little more complex. Migrating to Python 3 has this advantage among
many others.

 \       "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

More information about the Python-list mailing list