cascading python executions only if return code is 0

Cameron Simpson cs at zip.com.au
Sun Dec 22 16:39:46 EST 2013


On 22Dec2013 15:05, Roy Smith <roy at panix.com> wrote:
> In article <mailman.4504.1387740695.18130.python-list at python.org>,
>  Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> 
> > On 22/12/2013 19:17, Roy Smith wrote:
> > > In article <mailman.4500.1387739297.18130.python-list at python.org>,
> > >   Frank Cui <ycui at outlook.com> wrote:
> > >> I have a requirement where I need to sequentially execute a bunch of
> > >> executions, each execution has a return code. the followed executions 
> > >> should
> > >> only be executed if the return code is 0. is there a cleaner or more 
> > >> pythonic
> > >> way to do this other than the following ?
> > >> if a() == 0:    if b() == 0:        c()
> > >
> > > Yup!  Just do:
> > >
> > > a() or b() or c()
> > >
> > > The "or" operation has what's known as "short-circuit" semantics.  That
> > > means, if the first operand is true, it doesn't evaluate the second
> > > operand.  Just make sure that a(), b(), and c() all return something
> > > which is true if they succeed and false otherwise.
> > 
> > Really? :)
> 
> I believe what Mark is so elegantly trying to say is, "Roy is a dufus 
> and got that backwards".  You need to return something which is false to 
> make the next one in the chain get executed.
> 
> $ cat or.py 
> def a():
>     print "a"
>     return 0
> 
> def b():
>     print "b"
>     return 1
> 
> def c():
>     print "c"
>     return 0
> 
> a() or b() or c()
> 
> 
> $ python or.py
> a
> b

Yeah.

Roy's code _depends_ upon the return value being equivalent to False.

A better approach would be:

  a() == 0 and b() == 1 and c() == 0

i.e. to explicitly check each return code against the expected/desired
value instead of relying on some flukey coincidental property of
the (arbitrary) numeric value returned.

Better still is the suggestion elsewhere in the thread to make the functions
raise exceptions on error instead of returning a number.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list