0

Sometimes I need to consecutively check several conditions in Python.

I know, that in Python we're encouraged to avoid using too many nested IF-statements, and there are several ways to do that.

For example, you can flatten them into a one-liner:

if condition1 and condition2 and condition3:
  do_stuff()

Or create a boolean variable, containing the result of all the condition checks and then check that variable.

But sometimes, I can't avoid using nested IF-statements, because they absolutely have to be checked in that particular order, otherwise, if condition1 isn't met, then trying to check condition2 might lead to an exception. E.g.:

# var must be a list of numpy arrays
if var is not None:  # is it not Null?
  if isinstance(var, list):  # is it really a list?
    for v in var:
      if isinstance(v, numpy.ndarray):  # is it really a numpy array?
        if len(v.shape) == 3:   # does it have three dimensions?
          if v.shape[2] == 3:   # does it have three channels?
            v = cv2.cvtColor(v, cv2.COLOR_BGR2HSV)  # then convert RGB to HSV

Now, this is of course a synthetic example, and I generally don't write code like that. But you can clearly see, that if you try to check these conditions and the same time as one line, you'll get an exception. Unless you put everything in a try...except block of course.

Of course, sometimes, if you're doing it inside a function, it is possible to do these checks one by one and just exit the function earlier by returning a "FAILURE" result:

def foo(var):
  if var is None:
    return False

  if not isinstance(var, list):
    return False

  if len(var) == 0:
    return False

  ...
  # and so on

But sometimes, I find myself unable to do that and I absolutely have to do these as nested IF-statements.

Question: is there a standard way in Python to avoid that, when the 'one-liner' and 'early exit' solutions are unavailable?

xonxt
  • 363
  • 1
  • 2
  • 13
  • 1
    Check out short-circuiting. Python checks the truth of boolean requests from left to right. You can pull them together in a single if-statement. – James Sep 19 '19 at 08:46
  • using a function (or multiple functions is normally the way to go). sometimes you can use `continue` statements to avoid nesting also, e.g. `if var is None: continue` etc. – Chris_Rands Sep 19 '19 at 08:46
  • or if `all(condition for condition in list_of_conditions): do_stuff` – Chris_Rands Sep 19 '19 at 08:47
  • @James huh... I haven't realized, that Python chains the conditions. Never though to actually check (coming from other languages like C++ and Java). Thanks. – xonxt Sep 19 '19 at 15:03

0 Answers0