A small proposed change to dictionaries' "get" method
jepler epler
jepler.lnk at lnk.ispi.net
Thu Aug 3 18:41:37 EDT 2000
My two cents:
import UserDict, copy
class DefaultingDict(UserDict.UserDict):
def __init__(self, default=None):
self.default = default
UserDict.UserDict.__init__(self)
def __getitem__(self, key):
try:
return self.data[key]
except:
self.data[key] = copy.copy(self.default)
return self.data[key]
def _test():
x = DefaultingDict(0)
x[1] = 1
print x[0]
print x[1]
x = DefaultingDict([])
print x[0]
x[0].append("item")
print x[0]
x[0].append("item2")
print x[0]
if __name__ == '__main__': _test()
More information about the Python-list
mailing list