How to properly override the default factory of defaultdict?
ben+python at benfinney.id.au
Sun Feb 14 19:36:45 EST 2016
Herman <sorsorday at gmail.com> 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.)
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):
> return dict.__getitem__(self, key)
you are using the inheritance hierarchy but thwarting it by not using
super().__init__(self, default_factory, *a, **kw)
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
\ "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 |
More information about the Python-list