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.
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.
GetBelowObject
Using a loop for:
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
if a: if b: return c return d
if s:
if not a: return d if not b: return d return c