Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an empty return in Python mean? [duplicate]

Tags:

python

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?

like image 486
micgeronimo Avatar asked Feb 05 '15 09:02

micgeronimo


People also ask

Is return the same as return None?

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.

What happens if return is missing in Python?

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.

How do you return a blank value in Python?

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').

What is empty method in Python?

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").


2 Answers

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
like image 200
Padraic Cunningham Avatar answered Oct 16 '22 08:10

Padraic Cunningham


return exits the current function.

So, here it will stop the execution & return None.

like image 9
Hare Kumar Avatar answered Oct 16 '22 07:10

Hare Kumar