How to avoid protective conditions in python?

I am writing code that tries to delve deeply into the input object and detect the value that lies inside this object. Here is a sample code:

def GetThatValue(inObj):
    if inObj:
       level1 = inObj.GetBelowObject()
       if level1:
           level2 = level1.GetBelowObject()
           if level2:
               level3 = level2.GetBelowObject()
               if level3:
                  return level3.GetBelowObject()
    return None

There are many situations where I end up with these “downhill conditions”. How can i avoid this? It looks dirty and it's a kind of defensive programming.

+4
source share
2 answers
try:
    return monkey.TypeWriter().Manufacturer().Shareholders().EthnicDistribution()
except AttributeError:
    return None

Try to get a thing. If it does not work, you know that one of the levels is missing. This works especially well if these calls GetBelowObjectare not actually the same method.

+4
source

Using a loop for:

def GetThatValue(inObj):
    for i in range(4):
        if not inObj:
            break # OR return None
        inObj = inObj.GetBelowObject()
    return inObj

UPDATE

if. .

, if s:

if a:
    if b:
        return c
return d

if s:

if not a:
    return d
if not b:
    return d
return c
+9

All Articles