KeyError without [] harmful?

John J. Lee jjl at pobox.com
Mon May 12 18:25:17 EDT 2003


Sometimes I have methods that work rather like dictionary access, but
whose class for one reason or another can't sensibly be given a real
mapping interface (with __getitem__ etc).

Consider this class for example, that has a method that works a bit
like

del mydict[key]

but actually works like (and is implemented in terms of) a 'two-level
dictionary' -- ie. a dictionary of dictionaries.

class Things:
# self.things is a dictionary of dictionaries of things
...
    def clear_things(self, key1=None, key2=None):
        if key1 is not None:
            # clear everything under key1 and key2
            del self.cookies[key1][key2]
        elif key2 is not None:
            # clear everything under key1
            del self.cookies[key1]
        else:
            # clear everything
            self.things = {}


Strictly, I suppose it should raise ValueError if a dict lookup in
there fails, but part of me wants to just leave it at that and let the
KeyErrors propagate.  Is that a wicked thought?


John




More information about the Python-list mailing list