d = dictutil.DefaultDictWithEnhancedFactory(lambda k: k)
self.assertEqual("apple", d['apple'])
From: Ben Finney <[email protected]>
>
> 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 <[email protected]>
>
> 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" <[email protected]>
> > 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.
--
https://mail.python.org/mailman/listinfo/python-list