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


Groups > comp.lang.python > #102930

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

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: How to properly override the default factory of defaultdict?
Date 2016-02-15 12:04 +1100
Message-ID <mailman.125.1455498268.22075.python-list@python.org> (permalink)
References <CANOe_mhsAmLUYJ+7VfHWuOjKJwm=T59OVLyLRfasCYpqOAV-ZA@mail.gmail.com>

Show all headers | View raw


On Mon, Feb 15, 2016 at 11:17 AM, Herman <sorsorday@gmail.com> wrote:
> 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:

Save yourself a lot of trouble, and just override __missing__:

class DefaultDictWithEnhancedFactory(collections.defaultdict):
    def __missing__(self, key):
        return self.default_factory(key)

ChrisA

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


Thread

Re: How to properly override the default factory of defaultdict? Chris Angelico <rosuav@gmail.com> - 2016-02-15 12:04 +1100

csiph-web