[Python-ideas] except expression

Steven D'Aprano steve at pearwood.info
Thu Feb 13 22:38:37 CET 2014


On Thu, Feb 13, 2014 at 10:10:16PM +1100, Ben Finney wrote:
> spir <denis.spir at gmail.com> writes:
> 
> > 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()
> 
> Or, better from two perspectives (“empty” should normally entail
> “evaluates to boolean false”; and, the normal case should be the first
> branch from the “if”)::
> 
>     if col:
>         handle_standard_case()
>     else:
>         handle_empty_case()

I'm afraid that entails a race-condition. col may be non-empty at the 
moment you check it, but by the time you handle the non-empty case a 
microsecond later it has become empty.

This is why we have both Look Before You Leap and Easier To Ask 
Forgiveness Than Permission. We can perform LBYL in an expression using 
ternary if operator:

(handle_standard_case if col else handle_empty_case)()

but there's no equivalent to a try...except in a single 
expression, which is what this thread is about.


-- 
Steven


More information about the Python-ideas mailing list