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()
Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
FourOhFour
  • 121
  • 3

2 Answers2

5
if( expression1 and expression2):
 doSomething()
else:
 doSomethingElse()

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

DMS
  • 74
  • 2
  • 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 https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not – 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
  • I understand your concern to be as explicit as possible, that said, short circuiting like this is fairly common in many languages. Perhaps a quick comment in the else with a link to the docs would provide some comfort. – Newtopian Nov 21 '16 at 17:00
  • @Newtopian That's a good idea. Thanks for the help. – FourOhFour Nov 21 '16 at 17:21
1

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

if exp1 :
    if exp2 :
        doSomething()
        return

doSomethingElse()
Ewan
  • 70,664
  • 5
  • 76
  • 161
  • 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 01 '16 at 22:55