[Python-ideas] Default return values to int and float

Steven D'Aprano steve at pearwood.info
Sat Oct 8 13:23:01 CEST 2011


Ron Adam wrote:

> Sometime I feel exceptions are overly general.  Ok, so I got a
> ValueError exception from some block of code...  But is it the one I
> expected, or is it one from a routine in a library I imported and wasn't
> caught or handled correctly.  (ie.. my routine called a function in
> another module someone else wrote.)

I can't say I've very often cared where the exception comes from. But 
that's because I generally wrap the smallest amount of code possible in 
an try...except block, so there's only a limited number of places it 
could come from.


> One answer to that is to  put the try except around the fewest lines of
> code possible so that it doesn't catch  exceptions that aren't related
> to some specific condition.

Exactly.


>   That leads to possibly quite a few more
> try-except blocks, and possibly more nested try-except blocks.  At some
> point, it may start to seem like it's a better idea to avoid them rather
> than use them.

Or refactor parts of your code into a function.


> What if you can catch an exception specifically from a particular
> function or method, but let other unexpected "like" exceptions bubble
> through...
> 
>    try:
>       ...
>       i = s.index('bar')
>       ...
>    except ValueError from s.index as exc:
>       <handle s.index ValueError>


I can't imagine that this would even be *possible*, but even if it is, I 
would say it certainly isn't *desirable*.

(1) You're repeating code you expect to fail: you write s.index twice, 
even though it only gets called once.

(2) The semantics are messy and unclear. Suppose you have this:

try:
     ...
     i = s.index(a)
     j = s.index(b) + s.index(c)
     t = s
     k = t.index(d)
     method = s.index
     l = method(e)
     ...
except ValueError from s.index:
     ...

Which potential s.index exceptions will get caught? All of them? Some of 
them? Only i and j? What if you want to catch only some but not others?

How will this construct apply if s or s.index is rebound, or deleted, 
inside the try block?

     s += "spam"
     m = s.index(f)


What about this?

     alist = ['spam', 'ham', s, 'eggs']
     results = [x.index('cheese') for x in alist]


Should your proposal catch an exception in the list comp?

What if you call a function which happens to call s.index? Will that be 
caught?

     x = some_function(spam, ham, s, eggs)  # happens to call s.index




-- 
Steven




More information about the Python-ideas mailing list