1

What is the best way to implement the following code without having the same code duplicated in two different blocks, but while maintaining efficiency and readability?

if (expression1):
    if (expression2 that can only be checked if expression1):
        doSomething()
    else:
        doSomethingElse()
else:
    doSomethingElse()
5
if( expression1 and expression2):
 doSomething()
else:
 doSomethingElse()

Since Python supports short-circuit evaluation, Expression2 will only be evaluated if expression1 is true.

| improve this answer | |
  • I am aware that this is the case but this I'm pretty sure that this behaviour isn't guaranteed by the spec and explicit is better than implicit, right? I think this hampers readability. – FourOhFour Nov 21 '16 at 16:42
  • 1
    It is a faily common idiom in some languages to use short-circuit evaluation this way. Eg. - The first expression will be to check a pointer is not null, and dereference the pointer in the second expression. – DMS Nov 21 '16 at 16:52
  • But as I am not a python programmer, I will let someone else answer whether this would be idiomatic python or not... – DMS Nov 21 '16 at 16:53
  • 2
    it is explicitely stated in the python docs docs.python.org/3/library/… – Newtopian Nov 21 '16 at 16:54
  • Thank you @Newtopian, I was not aware that this was guaranteed. It still doesn't totally sit right with me but I think that's grounds for this to be the accepted answer. Thanks all! – FourOhFour Nov 21 '16 at 16:57
1

I like the AND answer, but you could also use early return.

if exp1 :
    if exp2 :
        doSomething()
        return

doSomethingElse()
| improve this answer | |
  • 2
    This worries me because it's easy to miss the return statement and assume that the doSomethingElse() will always be executed while skim-reading the code. Returning is not possible if more code need be executed after this block. – FourOhFour Nov 21 '16 at 16:56
  • yes, thats why people prefer the AND solution and functions – Ewan Nov 21 '16 at 16:57
  • 2
    .. and languages with {} – Ewan Nov 21 '16 at 16:58
  • @Ewan I don't get how braces can make the return more visible. If it's easy to miss there, it's easy to miss with braces too. – 301_Moved_Permanently Dec 1 '16 at 22:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.