Op 2005-03-21, Robert Kern schreef <[EMAIL PROTECTED]>: > Antoon Pardon wrote: >> Well at least I find them missing. >> >> For the moment I frequently come across the following cases. >> >> 1) Two files, each with key-value pairs for the same dictionary. >> However it is an error if the second file contains a key that >> was not in the first file. >> >> In treating the second file I miss a 'set' method. >> dct.set(key, value) would be equivallent to dct[key] = value, >> except that it would raise a KeyError if the key wasn't >> already in the dictionary. >> >> >> 2) One file with key-value pairs. However it is an error >> if a key is duplicated in the file. >> >> In treating such files I miss a 'make' method. >> dct.make(key, value) would be equivallent to dct[key] = value. >> except that it would raise a KeyError if the key was >> already in the dictionary. >> >> >> What do other people think about this? > > def safeset(dct, key, value): > if key not in dct: > raise KeyError(key) > else: > dct[key] = value > > def make(dct, key, value): > if key in dct: > raise KeyError('%r already in dict' % key) > else: > dct[key] = value > > I don't see a good reason to make these built in to dict type. >
I would say the same reason that we have get. There is no reason to have a builtin get it is easily implemented like this: def get(dct, key, default): try: return dct[key] except KeyError: return default I would go even so far that there is more reason to have a built-in safeset and make, than there is a reason to have a built-in get. The reason is that a python implementation of safeset and make, will mean two accesses in the dictionary, once for the test and once for the assignment. This double access could be eliminated with a built-in. The get on the other hand does only one dictionary access, so having it implemeted in python is a lesser burden. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list