catching exceptions from an except: block
Larry Bates
lbates at websafe.com
Wed Mar 7 15:52:28 EST 2007
Arnaud Delobelle wrote:
> Hi all,
>
> Imagine I have three functions a(x), b(x), c(x) that each return
> something or raise an exception. Imagine I want to define a function
> that returns a(x) if possible, otherwise b(x), otherwise c(x),
> otherwise raise CantDoIt.
>
> Here are three ways I can think of doing it:
>
> ----------
> # This one looks ugly
> def nested_first(x):
> try:
> return a(x)
> except:
> try:
> return b(x)
> except:
> try:
> return c(x)
> except:
> raise CantDoIt
>
> # This one looks long-winded
> def flat_first(x):
> try:
> return a(x)
> except:
> pass
> try:
> return b(x)
> except:
> pass
> try:
> return c(x)
> except:
> raise CantDoIt
>
> # This one only works because a,b,c are functions
> # Moreover it seems like an abuse of a loop construct to me
> def rolled_first(x):
> for f in a, b, c:
> try:
> return f(x)
> except:
> continue
> raise CantDoIt
> ----------
>
> I don't feel happy with any of these. Is there a more satisfying way
> of doing this in Python? What I would like is something like:
>
> ----------
> # This one isn't correct but looks the clearest to me
> def wished_first(x):
> try:
> return a(x)
> except:
> return b(x)
> except:
> return c(x)
> except:
> raise CantDoIt
> ----------
>
> I guess what I'm looking for is some sort of
> if:
> elif:
> ...
> elif:
> else:
>
> but for try: except:
> That's why
> try:
> except:
> except:
> ...
> except:
>
> seemed natural to me :) And I'd like to find a nice way to do this in
> a syntactically correct way.
>
> Note: I've chosen functions a, b, c, but really I'm looking for a way
> that is suitable for any chunk of code.
>
Without knowing more about the functions and the variable it is somewhat
hard to tell what you are trying to accomplish. If a, b, c are functions
that act on x when it is a different type, change to one function that
can handle all types.
def d(x):
if isinstance(x, basestring):
#
# Code here for string
#
elif isinstance(x, int):
#
# Code here for int
#
elif isinstance(x, float):
#
# Code here for string
#
else:
raise ValueError
If they are different functions based on type do something like this:
#
# Set up a dictionary with keys for different types and functions
# that correspond.
#
fdict={type(''): a, type(1): b, type(1.0): c}
#
# Call the appropriate function based on type
#
fdict[type(x)](x)
-Larry
More information about the Python-list
mailing list