Dictionary Enhancement?

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Oct 31 16:06:23 CET 2002


>>>>> "Rich" == Rich Harkins <rich at worldsinfinite.com> writes:

    Rich> I was wondering if anyone else had been wanting to enhance
    Rich> Python dictionaries such that instead of raising KeyError in
    Rich> the case of errors that another method on the dictionary
    Rich> object, say __makeitem__ would be called to try to
    Rich> auto-generate an appropriate value.  That __makeitem__
    Rich> method would then either raise KeyError itself or return the
    Rich> value to insert into the dictionary and return through
    Rich> __getitem__.

As of python 2.2, you can subclass built in types, so you are free to
enhance dict anyway you like.

Here is an example that uses makeitem to cube the argument, and raises
a KeyError if it can't

# requires python2.2
class mydict(dict):

    def __makeitem__(self, key):
        try: val = key**3
        except: raise KeyError
        else: return self.setdefault(key, val)
        
    def __getitem__(self, key):
        return self.get(key, self.__makeitem__(key))

m = mydict()

print m[2]  # this is ok
m[3] = 10   # so is this

m['John'] = 33
#print m['Bill']  this raises a key error


print m

Is this what you are looking for?

John Hunter




More information about the Python-list mailing list