Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #103139

Re: How to properly override the default factory of defaultdict?

From Herman <sorsorday@gmail.com>
Newsgroups comp.lang.python
Subject Re: How to properly override the default factory of defaultdict?
Date 2016-02-18 09:41 -0800
Message-ID <mailman.17.1455817335.2289.python-list@python.org> (permalink)

Show all headers | View raw


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

From: Ben Finney <ben+python@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@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@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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: How to properly override the default factory of defaultdict? Herman <sorsorday@gmail.com> - 2016-02-18 09:41 -0800

csiph-web