jeudi 19 septembre 2019

Q: Consecutive nested IF statements in Python [duplicate]

This question already has an answer here:

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?

Aucun commentaire:

Enregistrer un commentaire