When looking through Python code on GitHub, I've seen several examples of a return
with no value. For example:
if hasattr(self, 'moved_away'):
return
# and here code continues
What does the empty return mean?
As other have answered, the result is exactly the same, None is returned in all cases. The difference is stylistic, but please note that PEP8 requires the use to be consistent: Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should.
Without the final return, the flow of control reaches the end of the function without hitting a return statement, so the default value of None is returned.
If you want to return a null function in Python then use the None keyword in the returns statement. Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing').
An empty function is a function that does not contain any statement within its body. If you try to write a function definition without any statement in python – it will return an error ("IndentationError: expected an indented block").
It means it will return None
. You could remove the return
and it would still return None
because all functions that don't specify a return value in python will by default return None
.
In this particular case it means the code will go no further if the object has the attribute 'moved_away'
, without the return any code below would be evaluated even if the if
statement evaluated to True.
So you can think of it as being similar to a break statement in a loop when you have a condition you want to exit the loop on, without the break the code would continue to be evaluated.
if hasattr(self, 'moved_away'): # if this is True we return/end the function
return
# if previous statement was False we start executing code from here
return
exits the current function.
So, here it will stop the execution & return None
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With