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
786

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
56

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      
Discussions

What to return for no value if Null and nothing are valid?
What you are looking for is called a sentinel value. Python dataclasses module uses this approach to indicate missing values, and you can look up the implementation here (it’s very similar to what u/FerricDonkey recommended). Edit: punctuation More on reddit.com
🌐 r/learnpython
22
15
June 9, 2024
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
None,Nan or NA as a return value
Not sure where this belongs in ... to ignition i found this interesting and now have questions. Normally when using an object where there is "Null" data i would have expected "" or null as a return len()=0, however i got a "None" len()=4 return when something is not present. Question's is this some sort of python thing? can ... More on forum.inductiveautomation.com
🌐 forum.inductiveautomation.com
1
0
March 29, 2023
FastAPI returns null even though i return a value back. : Forums : PythonAnywhere
I'm a bit new to python so bear with me with my crappy coding. No matter what i do i keep getting null when hitting my reviews endpoint. Thanks you all for your help.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import json ... def __init... More on pythonanywhere.com
🌐 pythonanywhere.com
July 2, 2024
🌐
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 ...
🌐
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
🌐
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 - Boolean: bool is a fundamental data type in Python, representing the two truth values: True and False. Functions can return boolean values to represent success or failure, or other binary conditions. ... Python functions can return various types of results or even no results. This section discusses different ways a Python function can return nothing, specifically: Return None, Return Null, and Return NaN.
🌐
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 ...
🌐
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?
June 9, 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

Find elsewhere
Top answer
1 of 16
103

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
102

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.

🌐
NxtWave
ccbp.in › blog › articles › null-in-python
Null in Python: Understanding and Handling Null Values
January 27, 2025 - When working with datasets, missing values often appear as None (or null in other systems). It's essential to handle missing data before performing any calculations to avoid errors. ... def clean_dataset(data): # Replace None with a default value or handle it as required return [item if item is not None else 0 for item in data] data = [10, None, 20, None, 30] cleaned_data = clean_dataset(data) print(cleaned_data) # Output: [10, 0, 20, 0, 30]
🌐
Mimo
mimo.org › glossary › python › none-null
Python Null: Null in Python | Learn Now
Understanding how None compares to these can clarify its unique role in Python code. ... # `None` is a singleton a = None b = None print(a is b) # Outputs: True # Comparing None with True and False print(None is True) # Outputs: False print(None is False) # Outputs: False · None can be used to handle the absence of any return data in functions that might otherwise raise an exception.
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 34805
FastAPI returns null even though i return a value back. : Forums : PythonAnywhere
July 2, 2024 - I'm a bit new to python so bear with me with my crappy coding. No matter what i do i keep getting null when hitting my reviews endpoint. Thanks you all for your help. <br> from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import json ... def __init...
🌐
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 ...
🌐
Beust
beust.com › weblog › its-okay-to-return-null
It’s okay to return null « Otaku – Cedric's blog
This is based on my experience with Python, which was initially fueled by Django (as seems to be the case with Marty), but has moved to other areas. As such, it’s common to throw exceptions. The alternative is to ask for permission first, which means either using dict.has_key() or the “in” keyword. I’ve grown into a habit of using the latter. “if key in dict: blah = dict[key]”. I view this as idiomatically similar to doing null checks in Java.
🌐
Codedamn
codedamn.com › news › python
What Is Null in Python? NoneType Object Explain
December 5, 2022 - Here is an example where we put a null-type object inside a variable and print its value. def var1 = none print(var1)Code language: Python (python) Even if you put nothing inside the variable, Python automatically puts value inside the variable. So, if you just declare the variable and assign nothing to it then you should expect to get a None value in return but that is not the case.
🌐
Django Forum
forum.djangoproject.com › using django
Form return None Value - Using Django - Django Forum
September 10, 2021 - Hi Guys, When a user fill out a form, sometime, he do not put an information. So, the field is empty. The result in Django (Reuest.POST Form) is a None value. Is there a way to change this None value to an empty valu…
🌐
Python.org
discuss.python.org › python help
Print returning none - Python Help - Discussions on Python.org
November 8, 2022 - Hi everyone, I started self learning python and I have no background of programming before. Trying to self study from youtube. I’m practicing if else, while and so on but for some reason the print is returning none. …
🌐
FavTutor
favtutor.com › blogs › null-python
Null in Python: How to set None in Python? (with code)
August 17, 2023 - Python doesn't have an attribute with the term null, to speak specifically. Python uses None in place of null. It's used to specify a null value or absolutely no value.
🌐
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)
🌐
Real Python
realpython.com › null-in-python
Null in Python: Understanding Python's NoneType Object – Real Python
December 15, 2021 - You modify good_function() from above and import Optional from typing to return an Optional[Match]. In many other languages, null is just a synonym for 0, but null in Python is a full-blown object: