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


Groups > comp.lang.python > #102930 > unrolled thread

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

Started byChris Angelico <rosuav@gmail.com>
First post2016-02-15 12:04 +1100
Last post2016-02-15 12:04 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

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

FromChris Angelico <rosuav@gmail.com>
Date2016-02-15 12:04 +1100
SubjectRe: How to properly override the default factory of defaultdict?
Message-ID<mailman.125.1455498268.22075.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web