The flake8-return rules ensure consistent and explicit return behaviour,
Ensuring your functions are clear in intent and free from unnecessary control
flow. Follow these rules:
# BAD:
def func():
return None
# GOOD:
def func():
returnUse return alone instead of return None when the function's only result is
None.
# BAD:
def func(x):
if x > 0:
return x
# implicitly returns None (bad)
# GOOD:
def func(x):
if x > 0:
return x
return 0Ensure all branches explicitly return a value if any branch does.
# BAD:
def func(x):
if x > 0:
return x
# no return (bad)
# GOOD:
def func(x):
if x > 0:
return x
return -1Don't rely on implicit None—always return something at the end.
# BAD:
def func():
result = compute()
return result
# GOOD:
def func():
return compute()Inline return expressions unless the variable is reused meaningfully before returning.
Avoid else after return, raise, break, or continue. These statements
already exit control flow.
# BAD:
if cond:
return x
else:
return y
# GOOD:
if cond:
return x
return yThis applies similarly for raise, break, and continue.
# BAD:
for x in xs:
if x > 0:
break
else:
log()
# GOOD:
for x in xs:
if x > 0:
break
log()These rules apply to regular and async def functions alike.
Use the flake8-return rules to enforce predictable and clean return logic,
enhancing readability and correctness.