[Python-Dev] Proposal: defaultdict (original) (raw)
Bernhard Herzog bh at intevation.de
Sat Feb 18 22:41:07 CET 2006
- Previous message: [Python-Dev] Proposal: defaultdict
- Next message: [Python-Dev] Proposal: defaultdict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
"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):
try:
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) dd["abc"].append(1) dd["abc"].append(2) dd["def"].append(1) 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 onmissing() 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.
Bernhard
-- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/
- Previous message: [Python-Dev] Proposal: defaultdict
- Next message: [Python-Dev] Proposal: defaultdict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]