[Python-ideas] except expression

spir denis.spir at gmail.com
Thu Feb 13 12:02:03 CET 2014


On 02/13/2014 10:24 AM, Nick Coghlan wrote:
> General comment: like Raymond, I'm inclined to favour a nice expression
> friendly exception handling syntax, precisely because of the proliferation
> of relatively ad hoc alternative solutions (in particular, the popularity
> of being able to pass in default values to handle empty iterables).

I think the right way is not to call the function at all, but to check it. 
Conceptually:

   if col.is_empty():
       handle_special_case()
   else:
       handle_standard_case()

> One use case, for example, is handing IndexError when retrieving an item
> from a sequence (which currently has no nice standard spelling, and isn't
> amenable to the "pass in a default answer" solution because it isn't a
> normal function call).
>
> Another case not handled well by the status quo is when the default answer
> is expensive to calculate for some reason, so you really only want to
> calculate it if you actually need it.

The above schema applies to all cases where the failure (for the called service 
to perform its task) is _predictable_ by the client. Exceptions, in my view, are 
only for cases where the failure is impredictable (see below) *and* nevertheless 
belongs to to the application semantics; meaning, it does not result from a 
programming error (eg the collection should _not_ be empty), else one should not 
use exception catching, but instead let an error message helpfully inform us 
about the logical error.

Typical cases of impredictability on the client side are search/find functions, 
and dealing with the outer world, in particular the file system. In addition, in 
such cases using for instance a 'has' function (or in python 'in') to first 
check would do the job (of searching) twice. This is why, probably, there are 
alternative funcs like python's 'get' for dicts. Maybe this scheme could be 
generalised: not only eg list.get(i, default), but all cases of potentially 
failing funcs that return a result.

For functions (actions, in fact) that instead perform an effect, cases are more 
diverse and not always in our hands. For instance, one may think at a func which 
would create file if not existant, instead of replacing its contents (or 
appending to it): but this would I guess require the filesystem to provide such 
a facility. As far as I know, we are left with having routines search twice (for 
the abstract file location in the dir tree).

d


More information about the Python-ideas mailing list