What is the real benefit of obeying R1705 in pylint? Is the code really safer?
If you're trying to conform to Mozilla Coding Style or similar then R1705 makes sense. Quoting:
Don't put an else right after a return (or a break). Delete the else, it's unnecessary and increases indentation level.
Otherwise, you might prefer to disable that warning.
Better still, consider switching to flake8
,
which tends to stay pretty silent if you've been writing sensible code.
Outside of the Mozilla community,
most folks would rather see simple parallel functional clauses
handled with an else
, like this:
def max(a, b):
if a > b:
return a
else:
return b
This post gives two different cases for this design decision:
Guard clauses.
def try_something() if precondition(): result = compute_something() return result else: display_error() return None
The author argues that for several such conditions their inversion and implicit else
is better:
# Implicit else, inverted condition
def try_something():
if not precondition_one():
display_error_one()
return
if not precondition_two():
display_error_two()
return
result = compute_something()
return result
Symmetrical clause.
# Explicit else def check_link(link) -> bool: if is_internal_link(link): return check_internal_link(link) else: return check_external_link(link)
I agree with the author that here explicit is better.
I would also cite a comment from that post, which says that this choice is a choice of paradigm:
- "Explicit else": "if-then-else" is treated as lazy computation and more suited in "functional-first" environments. If this "if-then-else" is applied to large datasets and code in F#, Scala, Haskel, Closure or even SQL - explicitness is preferred. Most probably language/platform itself will encourage to write "pure" code and discourage/make near impossible to make imperative stunts.
- "Implicit else/(explicit return)": computation depends on 100% on side-effects and result is combination of side-effects too. It's impossible to guarantee correctness in strict sense anyway, so explicit return becomes clear declaration: "Because of laws of physics in our Universe, this computation could work incorrect. In majority of such cases this default value will be returned".