nested exceptions?

Roy Smith roy at panix.com
Sat Apr 20 19:19:38 EDT 2002


I've got a dictionary whose keys are oids.  An oid is a string which looks 
like '1.3.6.1.4.3.5.66.3.4', and represents a tree-structured hierarchy.

I want to look an oid up in my dictionary, and if it's not there, I want to 
keep working my way up the tree until I find it.  Thus, if 
'1.3.6.1.4.3.5.66.3.4' isn't a key, I want to try '1.3.6.1.4.3.5.66.3', and 
then '1.3.6.1.4.3.5.66', and then '1.3.6.1.4.3.5', and so on until I find 
it (if nothing else, '1' is guaranteed to be a key).

What I've come up with uses recursion:

    def getBaseObject (self, objects, oid):
        try:
           return objects[oid]
       except KeyError:
           return self.getBaseObject (objects, self.getParentOid (oid)) 

    def getParentOid (self, oid):
        parts = oid.split ('.')
        parentParts = parts[:-1]
        return '.'.join (parentParts)

The only thing I'm not sure about is that as you recurse your way up the 
tree, you'll have multiple KeyError exceptions in the process of being 
handled, stacked on top of each other.  Are there any problems with that?

I suppose the alternative would be to write this using 
objects.has_key(oid), but the way I've got it now seems neater.

As far as efficiency goes, I expect the vast majority of the oids to exist 
as keys.  For those that don't, I believe all of them will require only a 
single exception to resolve, but I want to make sure I handle the general 
case.



More information about the Python-list mailing list