What does an empty return in Python mean? [duplica

2020-03-09 08:35发布

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?

标签: python
2条回答
淡お忘
2楼-- · 2020-03-09 08:57

return exits the current function.

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

查看更多
孤傲高冷的网名
3楼-- · 2020-03-09 09:06

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
查看更多
登录 后发表回答