[Python-Dev] Proposal: defaultdict

skip at pobox.com skip at pobox.com
Fri Feb 17 16:05:27 CET 2006


 Guido> Over lunch with Alex Martelli, he proposed that a subclass of
 Guido> dict with this behavior (but implemented in C) would be a good
 Guido> addition to the language.
Instead, why not define setdefault() the way it should have been done in the
first place? When you create a dict it has the current behavior. If you
then call its setdefault() method that becomes the default value for missing
keys.
 d = {'a': 1}'
 d['b'] # raises KeyError
 d.get('c') # evaluates to None
 d.setdefault(42)
 d['b'] # evaluates to 42
 d.get('c') # evaluates to 42
For symmetry, setdefault() should probably be undoable: deldefault(),
removedefault(), nodefault(), default_free(), whatever.
The only question in my mind is whether or not getting a non-existent value
under the influence of a given default value should stick that value in the
dictionary or not.
down-with-more-builtins-ly, y'rs,
Skip


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /