Robert Brewer wrote: > This seems a bit too easy to do "as needed" to warrant a new builtin, > but that's why we have proposals, I guess: > > class DefaultingDict(dict): > > def __init__(self, default): > self.default = default > > def __getitem__(self, key): > return self.get(key, self.default()) It would not necessarily have to be a builtin, but it should be part of the standard library somewhere. Having to write it anew everytime you need it is too tedious, so I usually have a try:except: block, doing the defaulting in the except: part. There would be also more semantic issues, such as whether has_key should always return True on a DefaultingDict. Your implementation is incomplete, too - .pop() should invoke the default function, as should .get(). Regards, Martin
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4