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
Answer from Padraic Cunningham on Stack Overflow
🌐
Reddit
reddit.com › r/python › return none or not to return none
r/Python on Reddit: return None or not to return None
June 7, 2013 -

Several weeks ago a was pursuing some of the posts here on python and stumbled on an article about bad programming habits. I cant find the article again for reference but right at the top was a heady warning to avoid returning a meaningful None. AT the time I thought, 'well thats just droll and I never do that anyway', but as it turns out I do it all the time. If the function finds the correct thing then return the correct thing otherwise just end the function and python will return None for you.

So do you guys do the same thing? Whats wrong with returning None in the first place? What strategies do you use to avoid returning None?

Top answer
1 of 5
787

On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.

Using return None

This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.

We've got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function.

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.

Using no return at all

This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

In the following example, we set person's mother's name and then the function exits after completing successfully.

def set_mother(person, mother):
    if is_human(person):
        person.mother = mother

Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.

2 of 5
57

Yes, they are all the same.

We can review the interpreted machine code to confirm that that they're all doing the exact same thing.

import dis

def f1():
  print "Hello World"
  return None

def f2():
  print "Hello World"
  return

def f3():
  print "Hello World"

dis.dis(f1)
    4   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    5   5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f2)
    9   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    10  5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f3)
    14  0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE            
        5 LOAD_CONST    0 (None)
        8 RETURN_VALUE      
🌐
Julianhysi
julianhysi.com › post › 4
Julian's Blog - Bare return vs return None vs no return
Every function in Python which does not hit a return statement, will implicitly return None.
🌐
Real Python
realpython.com › python-return-statement
The Python return Statement: Usage and Best Practices – Real Python
June 14, 2024 - There is no notion of procedure or routine in Python. So, if you don’t explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you. That default return value will always be None.
🌐
Reddit
reddit.com › r/learnpython › how to have python return nothing instead of none?
r/learnpython on Reddit: How to have Python return nothing instead of None?
February 3, 2022 -

Python and I are NOT getting along today.

I have the script below, which takes arguments like username and fromdate and passes it into the appropriate place in the URL (the link variable). Now, if the user just inputs username and doesn't input fromdate, Python will return None instead of nothing. Why do you do this, Python!? I never asked you to!

How can I avoid this monstrosity?

Command

main.py  -u jacksfilms

Script

import requests, re, argparse

parser = argparse.ArgumentParser()
parser.add_argument('-u','--username', required=False)
parser.add_argument('-from','--fromdate', required=False)
parser.add_argument('-to','--todate', required=False)
args = vars(parser.parse_args())
username = args['username']
fromdate = args['fromdate']
todate = args['todate']

link = "https://web.archive.org/cdx/search/cdx?url=twitter.com/{}/status&matchType=prefix&from={}&to={}".format(username,fromdate,todate)
data = []

c = requests.get(link).text
urls = re.findall(r'https?://[^\s<>"]+[|www\.^\s<>"]+', c)

for i, url in enumerate (urls):
    data.append(f"{i}: {url}\n")
    
print(data)
🌐
GitHub
github.com › python › mypy › issues › 4123
Empty return statement should be treated as return None · Issue #4123 · python/mypy
August 3, 2017 - Currently, this from typing import Optional def test_return(flag: bool) -> Optional[int]: if flag: return return 0 fails with return.py:6: error: Return value expected With return None there are no errors, as expected. mypy 0.530, python...
Published   Oct 16, 2017
Top answer
1 of 6
9
  1. Raise an IndexError if the item is not found. This is what Python's list does. (Or maybe return the index where the item should have lived when doing a binary search or similar operation.)

  2. Think about what your function does, logically: if it returns a list of all items in a DB that satisfy some criterion, and there are no such items, then it makes sense to return an empty list since that allows all the usual list operations (len, in) to function without the need for an explicit check.

    However, if the absence of the required items indicates inconsistency, then raise an exception.

  3. My previous remark applies especially to this case: it depends on what you're going to do with the value you get. An ordinary dict just raises a KeyError when a key is not found. You're replacing that exception with a value, so you should know which value makes sense in the context of your program. If no value does, then just let the exception fly.

That said, returning None is often a bad idea because it may obscure bugs. None is the default return value in Python, so a function returning it may indicate nothing more than its author's forgetting a return statement:

def food(what):
    if what == HAM:
        return "HAM!"
    if what == SPAM:
        return " ".join(["SPAM" for i in range(10)])
    # should raise an exception here

lunch = food(EGGS)    # now lunch is None, but what does that mean?
2 of 6
1

There is also another option not listed in the question: throwing an exception. It seems to be popular enough in python, and it's sometimes better to follow a common practice for your language than to look for an abstractly best solution.

As of your examples:

  1. I would consider -1 because that's what "".find does, or throwing a ValueError because that's what [].index does (I don't mean the first option is the best one). I would never use one-based indices, so the value 0 is a valid result and can't be used to represent emptyness.

  2. I would prefer an empty list because the caller is not guaranteed to be interested in emptyness as a special case. If I want to count all rows for several queries, I'd hate to handle None specially. If there is a logically distinct situation where the list of rows cannot be produced (as opposed to there are no matching rows), I would consider using None or throwing an exception for this case.

  3. The meaning of an example is unclear, especially given that None is a valid dictionary key. But if I had to use some special value where string is normally expected, I would prefer it to be None (and if you prefer an empty string, it's important to know for sure that you never need a valid empty string, representing nothing special but itself).

🌐
Designcise
designcise.com › web › tutorial › how-to-return-nothing-or-null-from-a-python-function
How to Return Nothing/Null From a Python Function? - Designcise
November 13, 2022 - In Python, there's no "null" keyword. However, you can use the "None" keyword instead, which implies absence of value, null or "nothing". It can be returned from a function in any of the following ways: By returning None explicitly; By returning ...
Find elsewhere
🌐
Finxter
blog.finxter.com › home › learn python blog › python return nothing/null/none/nan from function
Python Return Nothing/Null/None/NaN From Function - Be on the Right Side of Change
August 1, 2023 - In Python, a function returns None implicitly if there is no explicit return statement. However, you can also use the return statement followed by the keyword None to indicate that a function should return no value.
🌐
Python.org
discuss.python.org › ideas
Deprecate bare return statements - Ideas - Discussions on Python.org
August 9, 2019 - FWIW “bare returns” (i.e. return vs return None ) I find are unintuitive as well. I think much of what is being said about bare except can also be said about “bare returns”. And while I feel PEP-8 does make an attempt to clarify this: “”" Be consistent in return statements.
🌐
MyCleverAI
mycleverai.com › it-questions › is-it-better-to-return-none-or-return-an-empty-value-in-python
Is it better to return None or return an empty value in Python?
- Type: `None` has its own type, while an empty list, string, or dictionary have their respective types. - Usability: Returning None might require explicit checking (e.g., if result is not None:), while an empty value can often be used directly.
🌐
Quora
quora.com › In-Python-what-does-return-None-mean-if-inside-a-function-we-use-return-without-any-value
In Python, what does return None mean if inside a function we use return without any value? - Quora
Answer (1 of 4): You’re correct; just a simple [code ]return[/code] statement without a value will return [code ]None[/code] implicitly. The reason why this happens is because Python has no concept of void.
🌐
Finxter
blog.finxter.com › python-function-return-none-without-return-statement
Python Function Return None Without Return Statement – Be on the Right Side of Change
The Python return keyword allows you to define the return value of a function (e.g., return X). If you don’t explicitly set a return value or you omit the return statement, Python will implicitly return the following default value: None.
🌐
Reddit
reddit.com › r/learnpython › eli5 how does "none" work exactly?
r/learnpython on Reddit: ELI5 how does "None" work exactly?
October 6, 2023 -

I get the general idea that None is a type when there is no specific value to be return.

But I am just confused on how to explicitly have a value of "None" . I am still learning python so I want to understand in which case does a function returns the value of "None". Like, it would also be helpful is someone could share a short function that displays "None" , preferably with no "return".

I've search online and there was an example of print(print("hi")), I kind of get this, the interpreter displays the first print and the second one is "None" because there is no value.

Thanks in advance

🌐
Reddit
reddit.com › r/learnpython › is it bad practice to define functions with no return value?
r/learnpython on Reddit: Is it bad practice to define functions with no return value?
January 3, 2024 -

For example, I have a function that saves data as a csv file and this function does not have a return value.

I’m unsure as to whether or not this is bad practice? I could return 0 to indicate that the data saved successfully and 1 to denote otherwise, but I’ve already got Raise Error in the save function so this feels unnecessary.

🌐
Quora
quora.com › Why-does-the-programming-language-Python-return-none-instead-of-nothing
Why does the programming language Python return none instead of nothing? - Quora
Answer (1 of 3): If a function fails to return you would get Nothing back - if it returns but doesn’t have any value(s) to return then you get back [code ]None [/code]- not that python functions can return more than one thing at a time, may ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-return-null-in-python
How to return null in Python ? - GeeksforGeeks
July 23, 2025 - Instead, Python uses None to represent the absence of a value or a null value. We can simply return None when you want to indicate that a function does not return any value or to represent a null-like state.