Null in Python

Python null is None

In Python, there is no null. Instead, Python has None that represents null.

You can use an if-statement to check if a value is None in Python:

For example:

name = None

if name is None:
    print("None found")
else:
    print(name)

Output:

None found

Today, you are going to learn everything about None in Python.

History of Null Values in Programming

In programming, a null value means a parameter does not have a value (at least yet).

It is like a placeholder for when a variable is empty. It can also refer to default parameters that are not defined yet.

Null in programming

As a real-life example, let’s say you have a variable s that represents how much money you have.

  • If n == $100, you have 100 dollars
  • If n == $0, you have no money
  • If n == null, you haven’t checked if you have money or not. Thus in this example, null represents the case where you don’t know how much money you have.

Many programming languages represent this absence of value as null. However, in Python, None is used instead.

None in Python

In Python, a function automatically returns None when there is no return statement.

For example, let’s create a function that does not return anything. The simplest example is to define a function and omit its implementation using the pass statement:

def test():
    pass

Now you can call this function and print the “result”:

print(test())

Output:

None

As you can see, the function returns None.

Let’s see another example.

Python’s built-in print() function does not return anything. That means it automatically returns None.

To see this, you can print the result of a print() call:

print(print("Example"))

Output:

None

This does not print "Example" and only prints None is because print("Example") returns None.

Facts About None Object in Python

Here are some facts about the None object:

  • None is not the same as False.
  • An empty string is not the same as None.
  • None is also not a zero.
  • Any comparison with None returns False, except for comparing None with itself

These facts can be verified using code examples (open up your Python REPL to repeat):

>>> None is False
False

>>> None == ""
False

>>> None == 0
False

>>> None == "None"
False

>>> None == None
True

How to Use and Deal with None in Python

In Python, None represents the absence of a value.

You commonly use None to:

  • Make comparisons to see if a value is None or not.
  • Provide a default value for a function.

You also see NoneType in the traceback error messages. This is because you have an unexpected None value somewhere in the code and you try to use it.

None in Comparisons

None is commonly seen when making comparisons in Python.

To compare an object with None, use the identity operator is (and is not).

For example:

number = None
name = "Alice"

number is None    # Returns True
name is not None  # Returns True

Generally, to check if a value is None in Python, you can use the if...else statement.

For instance, let’s check if a name variable is None:

name = None

if name is None:
    print("None found")
else:
    print(name)

Output:

None found

None as a Default Parameter

A None can be given as a default parameter to a function. This means calling the function and omitting the parameter the default value of None is used.

For example, let’s create a function that greets a person only if a name is given as an argument:

def greet(name=None):
    if name is not None:
        print(f"Hello, {name}!")


greet()         # Prints nothing
greet("Alice")  # Prints "Hello, Alice!"

This function works such that:

  • If a name is not specified, it defaults to None. As a result, the function does nothing.
  • If a name is specified, the function greets the person with that name.

None as a default parameter is a perfectly valid approach to utilizing None in Python. If you take a look at the official documentation of Python, you see None used this way in the list.sort() method.

Debugging a NoneType in a Traceback

When writing Python code, you commonly stumble across an error like this one:

AttributeError: 'NoneType' object has no attribute 'SOMETHING'

If you see this or any other error with the word NoneType it means you are using None in a way it cannot be used.

In other words, something that is not supposed to be None is accidentally None.

For instance, let’s create a function that gives a list of names. Let’s use this function and print the names:

def give_names():
    ["Alice", "Bob", "Charlie"]

names = give_names()

for name in names:
    print(name)

Instead of printing the names, an error occurs:

TypeError: 'NoneType' object is not iterable

This happens because we forgot to return the names in the give_names() function. As you know, when a function does not use the return keyword, None is returned automatically. As a result of this little mistake, we try to iterate over the None object.

But the fix is simple—return the names from the function:

def give_names():
    return ["Alice", "Bob", "Charlie"]

names = give_names()

for name in names:
    print(name)

Now it works as expected:

Alice
Bob
Charlie

This is just one example of how to track down an error with NoneType.

Generally, if you see NoneType in an error message, you are trying to operate with None that should not be None.

None Object Under the Hood in Python

In many popular programming languages, null is just a 0 under the hood.

In Python, this is not true.

Just like everything else in Python, None is an object.

This is easy to verify by checking the type of None in Python REPL:

>>> type(None)
<class 'NoneType'>

The type of None is NoneType. This is because NoneType is the base class that implements the None object.

In Python, None is a singleton object. This means there is only one None in Python. No matter where you see None, it is always the same None.

Let’s verify this by creating multiple variables with None as their value and checking their id:

n1 = None
n2 = None
n3 = None

print(id(n1))
print(id(n2))
print(id(n3))

Output:

4398896592
4398896592
4398896592

All the variables return the same id. This means the “different Nones” are actually the same object.

None object in Python

This also implies the variables n1, n2, and n3 are also the same object because they point to the same None object.

None Is a True Constant in Python

None is an object in Python. But it is a special object you cannot modify.

Let’s see what happens if you try to modify the None object in Python:

>>> None = 50
SyntaxError: cannot assign to None

Also, you cannot add properties to the None object:

>>> None.length = 50
AttributeError: 'NoneType' object has no attribute 'length'

Modifying the None object is not possible, because it is a true constant in Python. As discussed earlier, this can cause errors and bugs in your code. Luckily, the error message is clear enough to tell you what is going on.

Subclassing the underlying type NoneType of None is not possible.

For instance:

class CustomNone(type(None)):
    pass

Result:

TypeError: type 'NoneType' is not an acceptable base type

Conclusion

Python null is called None. It is a special object that represents the absence of a value.

Any function that does not return anything automatically returns a None.

Comparing None evaluates to True only when comparing it with itself. Any other comparisons yield False.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

Python Interview Questions and Answers

Useful Advanced Features of Python

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published.