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


Groups > comp.lang.python > #102926

How to properly override the default factory of defaultdict?

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

Show all headers | View raw


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:

class DefaultDictWithEnhancedFactory(defaultdict):
    """Just like the standard python collections.dict,
    but the default_factory takes the missing key as argument.

    Args:
        default_factory: A function that takes the missing key as the
argument
        and return a value for the missing key.
        *a: arguments passing to the defaultdict constructor
        **kw: keyword arguments passing to the defaultdict constructor
    """
    def __init__(self, default_factory, *a, **kw):
        defaultdict.__init__(self, default_factory, *a, **kw)

    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            # Normally, you would expect this line to be
            # called for missing keys...
            return self.default_factory(key)
        except TypeError as ex:
            # However, this is actually getting called
            # because for some reason, defaultdict still
            # intercepts the __getitem__ call and raises:
            # TypeError: <lambda>() takes exactly 1 argument (0 given)
            # So we have to catch that instead...
            if "lambda" in str(ex):
                return self.default_factory(key)

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


Thread

How to properly override the default factory of defaultdict? Herman <sorsorday@gmail.com> - 2016-02-14 16:17 -0800
  Re: How to properly override the default factory of defaultdict? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2016-02-15 14:56 +1100
  Re: How to properly override the default factory of defaultdict? Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2016-02-15 21:28 +1300

csiph-web