06 May, 2010

Conditions: No Need for Extra "else"

Sometimes when I am writing code quickly and jumping between functions, I miss a bit obvious logic and end up having multiple "else" statements. Below are two examples doing the same thing. Here the logic itself is not important, this is just to make a note.
...
   if trueKey != "":
       modObj = pkgDict[trueKey]
       if modObj.__dict__.haskey(className):
           return modObj.__dict__[className]
       else:
           return None
   else:
       return None 

In above example, two else conditions are unnecessary and messy. Concise version,
...
    if trueKey != "":
        modObj = pkgDict[trueKey]
        if modObj.__dict__.haskey(className):
            return modObj.__dict__[className]

    return None