如何在python中避免防御?

Sad*_*ase 4 python defensive-programming

我正在编写一个代码,试图深入挖掘输入对象并找出位于该对象内的值.这是一个示例代码:

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
Run Code Online (Sandbox Code Playgroud)

在很多情况下,我最终会得到这些"倾斜的条件".我怎么能避免这个?这看起来很脏,也是一种防御性的编程.

fal*_*tru 9

使用for循环:

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

UPDATE

避免深层嵌套的if语句.检查例外情况,并提前返回.

例如,在嵌套ifs之后:

if a:
    if b:
        return c
return d
Run Code Online (Sandbox Code Playgroud)

可以转化为扁平if的:

if not a:
    return d
if not b:
    return d
return c
Run Code Online (Sandbox Code Playgroud)