On Dec 22, 2013, at 10:37 AM, 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()

I know I’m a little late to the game on this one. Good answers and interesting 
discussions (and sometimes not). In some situations, I might do something like 
the following. It depends on just how many functions your cascading, and how 
arbitrary or pluggable those are.

If your model is that you have a sort of todo list of functions to execute 
(more than 3 or so), you might want to separate the definition of that run list 
from the logic that executes them. Given something like:

def a():
  print(‘Aye’)
  return 0

def b():
  print(‘Bee’)
  return 0

def c():
  print(’See’)
  return 0

def d():
  print(‘Dee’)
  return 1

def e():
  print(‘Eee’)
  return 1

You do the nested if as you original proposed or the chained or as also 
proposed. Or you could put the commands in a list:

script = [
  a,
  b,
  c,
  d,
  e]

This gives you a nice succinct list of stuff that needs to be done, not to 
different if you’d just coded it with no or logic, e.g.

a
b
c
d
e

Refactoring/evolving them then feels the same.

To run the script we could do it the good ol’ C'ish way:

for step in script:
  if step() != 0:
    break

But we have more functional style stuff via builtins which can capture that 
pattern:

ranToEnd = all(step() == 0 for step in script)

So IF you’re use case lends itself to separation of the “list of stuff to do” 
and the “logic to execute said list”, then… this approach might be appealing.

Travis Griggs


-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to