Does it matter to use `if ... else` or `if ... return; {implicit else}`?

1.8k views Asked by At

These two patterns produce the same results. Does it matter which one is used? Why?

I prefer the second, it has less indentation and just looks cleaner to me, but I haven't seen it used much (in the places I've been). I don't want to settle on something and use it all over if it's ill advised for some reason.

IF...ELSE

if not packages:
    help('download')
else:        
    for p in packages:
        do_download(p)
        verify_md5(p)
        etc(p)

IF...RETURN; IMPLICIT ELSE

if not packages:
    help('download')
    return

for p in packages:            
    do_download(p)
    verify_md5(p)
    etc(p)
2

There are 2 answers

0
twasbrillig On

From The Zen of Python:

Flat is better than nested.

So the second approach is more Pythonic.

I personally find flat code easier to read than nested code, and less error-prone as well (having e.g. an else statement not properly lined up can be hard to debug). Of course, these are subjective judgments.

4
Leon On

It's a style thing... But I always prefer using else. As you clearly indicate in your question caption not having an else makes it implicit and I strongly believe in explicit code that is easy to read and understand.

Also from The Zen of Python

Explicit is better than implicit.