On 12/22/13 2:10 PM, Frank Cui wrote:
sorry, but what if I need to have different parameters in these functions ?
Frank, welcome to the group. Common convention is to put your response
below the exiting message, so that the conversation continues down the page.
(See my answer below... :)
> To: python-list@python.org
> From: breamore...@yahoo.co.uk
> Subject: Re: cascading python executions only if return code is 0
> Date: Sun, 22 Dec 2013 19:31:21 +0000
>
> On 22/12/2013 19:17, Roy Smith wrote:
> > In article <mailman.4500.1387739297.18130.python-l...@python.org>,
> > Frank Cui <y...@outlook.com> wrote:
> >
> >> hey guys,
> >> 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()
> >> Thanks for your input.
> >> frank
> >
> > 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? :)
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> --
> https://mail.python.org/mailman/listinfo/python-list
The most Python-natural way to deal with your problem would be to have
these functions not return status codes at all. Instead, have them
raise an exception if something goes wrong. Then you can invoke them
most naturally:
a()
b()
c()
Execution will continue as long as no exceptions are raised. If you
need to deal with the failure case also, then:
try:
a()
b()
c()
except Exception as e:
# do something here
Depending on how you want to deal with failures, you'd probably use your
own subclass of Exception, but this is the general idea.
Return codes can be awkward, especially in Python which has exception
integrated so fully into the language, library, and culture.
--
Ned Batchelder, http://nedbatchelder.com
--
https://mail.python.org/mailman/listinfo/python-list