catching exceptions from an except: block
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Wed Mar 7 17:58:18 EST 2007
Arnaud Delobelle a écrit :
> 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
You have to write the "chunks of code" anyway, don't you ? So just
adding a def statement above each chunk is not such a big deal.
Remember that you can define nested funcs, that will close over the
namespace of the enclosing one, so you dont necessarily have to pollute
the global namespace nor explicitly pass the whole environment to each
of these functions.
Using the generic higher order func I proposed in a previous answer:
def maincode(tati, pouffin):
def a():
# some
# code
# here
# that may raise
return foo
def b():
# some
# shorter chunk
return bar
def c():
# yet
# some
# other
# code
return quux
return trythese(a, b)()
Is it really less readable than:
def maincode(tati, pouffin):
try:
# some
# code
# here
# that may raise
return foo
except_retry: # the missing(???) keyword you're after
# some
# shorter chunk
return bar
except_retry:
# yet
# some
# other
# code
return quux
else:
raise CantDoIt
> 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