el_pup_le
el_pup_le

Reputation: 12179

if else return practice

Noob question I know, but I need it confirmed since this occurs so often to me. Is there any point in using elif: if you know that code won't be reached when previous block is true? Eg.

if foo:
  return x
elif bar:
  return y

Should just be:

if foo:
  return x
if bar:
  return y

Upvotes: 1

Views: 2898

Answers (5)

Matt Ball
Matt Ball

Reputation: 359776

I can see at least three reasons to prefer if/elif:

  • It makes it clear to readers of the code that the writer intended the conditions to be mutually exclusive
  • If the code is later refactored, changing early returns to a single late return, the semantics of if/elif won't break, but if/if might
  • It keeps the code style consistent with the rest of the codebase you're working in

and at least two reasons to prefer if/if:

  • It's less typing
  • It keeps the code style consistent with the rest of the codebase you're working in

That said, here's some recommended reading:

Upvotes: 7

Frankline
Frankline

Reputation: 40985

Multiple IF statements means your code will check all the IF conditions, whereas in case of elif:, if one IF condition satisfies it would not check other conditions. (As has been pointed out to me, this is ONLY true if none of the IF statements has to return from the code block)

In your case, it is OK to use the multiple IF statement.

Upvotes: 0

pyrospade
pyrospade

Reputation: 8078

If you know it won't be true, then don't waste the interpreter's time with checking it. If you use if it will be evaluated every time; however, elif will only be evaluated if the previous if condition was False. In this case you are using return, so you should be safe from that, but by changing logical flow based on a return is bad. You should have as few (preferably only one) code paths as possible. Also, it gives a clean, readable structure and makes the code path explicit. Readability counts, and explicit is better than implicit.

Upvotes: 1

Kyle Strand
Kyle Strand

Reputation: 16499

From the standpoint of the Python interpreter, no, there's no difference--or at least, there's no difference in terms of execution, though there may be some subtle difference in the way the two constructs are implemented.

But keep in mind that you are writing not just to the interpreter; you're writing for other programmers to read your code later. Write whatever you think makes your intention most clear.

Upvotes: 1

Ian Clelland
Ian Clelland

Reputation: 44112

There isn't any difference to the python interpreter; in fact, the two code snippets will internally compile to the same instructions (the compiler is smart enough to know that the code after the return will never be reached, and will optimize the else part away completely.).

It's a matter of style, and readability.

Upvotes: 3

Related Questions