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


Groups > comp.lang.python > #103227

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

From Ian Kelly <ian.g.kelly@gmail.com>
Newsgroups comp.lang.python
Subject Re: How to properly override the default factory of defaultdict?
Date 2016-02-19 17:24 -0700
Message-ID <mailman.6.1455927922.13884.python-list@python.org> (permalink)
References <CANOe_mhpR2AMYruiwfawOvoiupJjOiswK7eZ14557KEvcc4Khg@mail.gmail.com>

Show all headers | View raw


On Thu, Feb 18, 2016 at 10:41 AM, Herman <sorsorday@gmail.com> wrote:
> 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

You're using it incorrectly. If your class is named
DefaultDictWithEnhancedFactory, then the super call would be:

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

You pass in the current class so that super can look up the next
class. If you pass defaultdict instead, super will think that it's
being called *by* defaultdict and call the __init__ method on its own
superclass, dict, which has a different signature.
defaultdict.__init__ is effectively skipped.

> Look like inheriting from defaultdict is easier. I don't even  have to
> override the constructor as suggested by Chris Angelico above. Thanks.

True, although there's a faint code smell as this technically violates
the Liskov Substitution Principle; the default_factory attribute on
defaultdict instances is expected to be a function of zero arguments,
not one.

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


Thread

Re: How to properly override the default factory of defaultdict? Ian Kelly <ian.g.kelly@gmail.com> - 2016-02-19 17:24 -0700

csiph-web