catching exceptions from an except: block

Arnaud Delobelle arnodel at googlemail.com
Wed Mar 7 22:48:18 CET 2007


On Mar 7, 8:52 pm, Larry Bates <lba... at websafe.com> wrote:
[snip]
> 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.

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




More information about the Python-list mailing list