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()
0

2 Answers 2

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

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

7
  • 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. Commented Nov 21, 2016 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. Commented Nov 21, 2016 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... Commented Nov 21, 2016 at 16:53
  • 2
    it is explicitely stated in the python docs docs.python.org/3/library/… Commented Nov 21, 2016 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! Commented Nov 21, 2016 at 16:57
1

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

if exp1 :
    if exp2 :
        doSomething()
        return

doSomethingElse()
4
  • 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. Commented Nov 21, 2016 at 16:56
  • yes, thats why people prefer the AND solution and functions Commented Nov 21, 2016 at 16:57
  • 2
    .. and languages with {} Commented Nov 21, 2016 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. Commented Dec 1, 2016 at 22:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.