Is it ok to skip "return None"?
To expound on what others have said, I use a return None
if the function is supposed to return a value. In Python, all functions return a value, but often we write functions that only ever return None, because their return value is ignored. In some languages, these would be called procedures.
So if a function is supposed to return a value, then I make sure all code paths have a return, and that the return has a value, even if it is None.
If a function "doesn't" return a value, that is, if it is never called by someone using its return value, then it's ok to end without a return, and if I need to return early, I use the bare form, return
.
Yes, if you do not return any value from a Python function, it returns None. So, whether to explicitly return None is a stylistic decision.
Personally, I prefer to always return a value for clarity.
Yes and No.
In the simplest case, it is ok to skip "return None" because it returns None in only single negative condition.
But if there are nested condition evaluation and multiple scenarios where a function could return None. I tend to include them as visual documentation of the scenarios.
[Editing: Based on comment below]
return or return None
I prefer "return None" to bare "return" as It is explicit and later, no one will be in doubt if the return meant returning None or was it an error as something was missing.
Like you said, return None
is (almost) never needed.
But you should consider that the intention of your code is much clearer with an explicit return None
. Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps.