nested exceptions?

Delaney, Timothy tdelaney at avaya.com
Sun Apr 21 19:23:20 EDT 2002


> From: Roy Smith [mailto:roy at panix.com]
> 
> 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)

Try the following (self omitted because it doesn't need to be part of a
class):

def getBaseObject (objects, oid):
    """"""

    path = string.split(oid, '.')

    while path:
        try:
            return objects[string.join(path, '.')]
        except KeyError:
            del path[-1]

You can of course change string.join to a local name as

    join = string.join

but this is more straighforward. If no part of the path is in objects, None
will be returned (instead of the infinite recursion you get with your
implementation). You may wish to raise an exception instead.

Tim Delaney





More information about the Python-list mailing list