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.

Answer from user2032433 on Stack Overflow
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      
🌐
Reddit
reddit.com › r/learnpython › what to return for no value if null and nothing are valid?
r/learnpython on Reddit: What to return for no value if Null and nothing are valid?
February 28, 2024 -

I have a function that fills out a dictionary with the values of specific variables as I iterate through another function to track what the actual output for each is. One of the things I'm using this for is to catch errors, so if a variable doesn't get assigned I get a value error and handle that, adding <no value> to the dictionary instead of the actual value. I don't want to use None or a blank string since those could actually be the value of one of these variables. <no value> seems fine for what I need to do, but I'm wondering if there's some agreed upon "null" value that I could use here instead

Discussions

Why does the my code return none!? I’m a noob so I don’t know whether the question is overtly stupid or what😃
This returns none. Ideal behind program is to convert Celsius to Fahrenheit using Fahrenheit = (9/5) * celsius + 32 But when I write return (9/5) * c + 32 it gives the desired result Just curious on the difference between print ((9/5) * c + 32) and return More on discuss.python.org
🌐 discuss.python.org
0
July 25, 2021
How to return Null in python
null = None in python. Well, not exactly, but semantically More on reddit.com
🌐 r/learnprogramming
5
1
June 29, 2020
object oriented - Is it better to return NULL or empty values from functions/methods where the return value is not present? - Software Engineering Stack Exchange
I am looking for a recommendation here. I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined. Ta... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 17, 2011
Why does one version of my function return None, while the other works fine?
Inspired by the pipeline operator (|>) in other languages, I tried to implement a function to imitate it. When I use reduce to implement it, it results in None somewhere along the way, but another one using loops works just fine. from functools import partial, reduce from pprint import pprint ... More on discuss.python.org
🌐 discuss.python.org
0
October 26, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-return-null-in-python
How to return null in Python ? - GeeksforGeeks
July 23, 2025 - def my_function(): return None # Call the function and store #the returned value in the variable 'result' result = my_function() print(result) ... In Python, None is used to represent a null value or the absence of a result.
🌐
Quora
quora.com › How-do-you-return-a-null-in-Python
How to return a null in Python - Quora
Answer (1 of 3): Python functions return the object None by default. So you may assign any name to the result of a function without error, but if the return value is ommited from the function or the value you are returning is a name that has ...
🌐
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 - You can follow the same steps outlined in the Return None sub-section when you want to return a “null” value in Python.
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.3 documentation
2 days ago - If it is an integer, the array ... with null bytes. If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array. If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array. Without an argument, an array of size 0 is created. See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects. ... Return a new “bytes” ...
Find elsewhere
🌐
Esri Community
community.esri.com › t5 › python-questions › python-won-t-recognize-null-or-none › td-p › 499637
Python won't recognize NULL (or None) - Esri Community
July 25, 2019 - "Calculate Field for Contiguous" Field Name: Contiguous · Expression: Answer(!Contig_ID!) Code Block: def Answer(CI): if CI ==None: return "N" else: return "Y" I've read plenty of posts explaining that NULL == None in python, but this code only returns Y for all numeric values in Contig_ID.
🌐
Python.org
discuss.python.org › python help
Why does the my code return none!? I’m a noob so I don’t know whether the question is overtly stupid or what😃 - Python Help - Discussions on Python.org
July 25, 2021 - This returns none. Ideal behind program is to convert Celsius to Fahrenheit using Fahrenheit = (9/5) * celsius + 32 But when I write return (9/5) * c + 32 it gives the desired result Just curious on the difference between print ((9/5) * c + 32) and return
🌐
Real Python
realpython.com › python-return-statement
The Python return Statement: Usage and Best Practices – Real Python
June 14, 2024 - This kind of statement is useful ... as the null operation because they don’t perform any action. Note: The full syntax to define functions and their arguments is beyond the scope of this tutorial. For an in-depth resource on this topic, check out Defining Your Own Python ...
🌐
Copahost
copahost.com › home › null python: the complete guide to null values
Null Python: The Complete Guide to Null Values - Copahost
August 11, 2023 - Here are some examples of how we can apply it None in Python: ... def sum(a, b): if a is None or b is None: return None else: return a + b result = sum(5, None) print(result) # Output: None
Top answer
1 of 16
102

StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:

Returning null is usually the best idea if you intend to indicate that no data is available.

An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.

Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.

However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.

In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.

2 of 16
101

In all the code I write, I avoid returning null from a function. I read that in Clean Code.

The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.

In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.

The analogous C# (anti-)pattern is the Try... method:

public bool TryFindPerson(int personId, out Person result);

Now I know people have said they hate the Try... pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:

class FindResult<T>
{
   public FindResult(bool found, T result)
   {
       this.Found = found;
       this.Result = result;
   }

   public bool Found { get; private set; }
   // Only valid if Found is true
   public T Result { get; private set;
}

public FindResult<Person> FindPerson(int personId);

...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework. That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).

So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.

If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:

public Person GetPerson(int personId);

...and then I'd throw an exception if it was invalid. The Get... prefix implies that the caller knows it should succeed.

🌐
Python.org
discuss.python.org › python help
Why does one version of my function return None, while the other works fine? - Python Help - Discussions on Python.org
October 26, 2023 - Inspired by the pipeline operator (|>) in other languages, I tried to implement a function to imitate it. When I use reduce to implement it, it results in None somewhere along the way, but another one using loops works just fine. from functools import partial, reduce from pprint import pprint def pipeline(data, *funcs): res = data for func in funcs: res = func(res) return res def pipeline_v2(data, *funcs): reduce(lambda arg, func: func(arg), funcs, data) def main() ->...
🌐
LearnPython.com
learnpython.com › blog › null-in-python
Null in Python: A Complete Guide | LearnPython.com
April 21, 2022 - Note that it’s important to use the identity operators (like is None and is not None) with the None objects in Python and not the equality operators like == and !=. The issue is that the equality operators can output wrong results when you’re comparing user-defined objects that override them. Here is an example: class EquityVsIdentity(): def __eq__ (self, other): return True check = EquityVsIdentity() print(check == None) print(check is None)
🌐
Apache Spark
spark.apache.org › docs › latest › sql-ref-null-semantics.html
NULL Semantics - Spark 4.1.1 Documentation
This class of expressions are designed to handle NULL values. The result of the expressions depends on the expression itself. As an example, function expression isnull returns a true on null input and false on non null input where as function coalesce returns the first non NULL value in its list of operands.
🌐
Refactoring.Guru
refactoring.guru › home › techniques › simplifying conditional expressions
Introduce Null Object
January 1, 2025 - Change the code so that it returns a null object. Find all places where the variables of the real class are compared with null. Replace these checks with a call for isNull(). If methods of the original class are run in these conditionals when a value doesn’t equal null, redefine these methods in the null class and insert the code from the else part of the condition there.
🌐
Python
docs.python.org › 3 › c-api › exceptions.html
Exception Handling — Python 3.14.3 documentation
On Unix, when the errno value is EINTR, indicating an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returns NULL, so a wrapper function around a system call can write return PyErr_SetFromErrno(type); when the system call returns an error.
🌐
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)
🌐
Medium
paul-d-chuang.medium.com › python-better-if-x-none-than-if-not-x-3d6cce484606
Python null check: better if x is not None than if not x | by Paul Chuang | Medium
January 10, 2025 - class Custom: def __ne__(self, other): # returned value for "!=" (ne means not equal) return False x = Custom() if x != None: print("x is not equal to None") # nothing will printed as x != None is False