[Python-Dev] Proposal: defaultdict

Bernhard Herzog bh at intevation.de
Sat Feb 18 22:41:07 CET 2006

"Guido van Rossum" <guido at python.org> writes:

> If the __getattr__()-like operation that supplies and inserts a
> dynamic default was a separate method, we wouldn't have this problem.

Why implement it in the dictionary type at all?  If, for intance, the
default value functionality were provided as a decorator, it could be
used with all kinds of mappings.  I.e. you could have something along
these lines:

class defaultwrapper(object):

    def __init__(self, base, factory):
        self.__base = base
        self.__factory = factory

    def __getitem__(self, key):
            return self.__base[key]
        except KeyError:
            value = self.__factory()
            self.__base[key] = value
            return value

    def __getattr__(self, attr):
        return getattr(self.__base, attr)

def test():
    dd = defaultwrapper({}, list)
    assert sorted(dd.keys()) == ["abc", "def"]
    assert sorted(dd.values()) == [[1], [1, 2]]
    assert sorted(dd.items()) == [("abc", [1, 2]), ("def", [1])]
    assert dd.has_key("abc")
    assert not dd.has_key("xyz")

The precise semantics would have to be determined yet, of course.

> OTOH most reviewers here seem to appreciate on_missing() as a way to
> do various other ways of alterning a dict's __getitem__() behavior
> behind a caller's back -- perhaps it could even be (ab)used to
> implement case-insensitive lookup.

case-insensitive lookup could be implemented with another
wrapper/decorator.  If you need both case-insitivity and a default
value, you can easily stack the decorators.


Intevation GmbH                                 http://intevation.de/
Skencil                                           http://skencil.org/
Thuban                                  http://thuban.intevation.org/

More information about the Python-Dev mailing list