catching exceptions from an except: block

garrickp at gmail.com garrickp at gmail.com
Wed Mar 7 17:04:25 EST 2007


On Mar 7, 2:48 pm, "Arnaud Delobelle" <arno... at googlemail.com> wrote:
>
> I'm not really thinking about this situation so let me clarify. Here
> is a simple concrete example, taking the following for the functions
> a,b,c I mention in my original post.
>   - a=int
>   - b=float
>   - c=complex
>   - x is a string
> This means I want to convert x to an int if possible, otherwise a
> float, otherwise a complex, otherwise raise CantDoIt.
>
> I can do:
>
> for f in int, float, complex:
>     try:
>         return f(x)
>     except ValueError:
>         continue
> raise CantDoIt
>
> But if the three things I want to do are not callable objects but
> chunks of code this method is awkward because you have to create
> functions simply in order to be able to loop over them (this is whay I
> was talking about 'abusing loop constructs').  Besides I am not happy
> with the other two idioms I can think of.
>
> --
> Arnaud

Wouldn't it be easier to do:

if isinstance(x, int):
    # do something
elif isinstance(x, float)t:
    # do something
elif isinstance(x, complex):
    # do something
else:
    raise CantDoIt

or,

i = [int, float, complex]
for f in i:
    if isinstance(x, f):
        return x
else:
    raise CantDoIt




More information about the Python-list mailing list