Python NoneType

In this tutorial we are going to discuss about Python NoneType. Before we start discussion on NoneType let us first see what is an object.

In any programming language preliminary data types are int, float, char etc. and we can create a class by mixing different data types together and the instances of these classes are called as object.

Take this for example:

Here stu is and object of class student.

When stu = student() is executed an object is created but what if we want to create the object stu but does not want to assign any value.

Here we can use None keyword.

None is actually an object of the class NoneType. When we write

stu = None we are actually pointing to an object of the class NoneType which always have a special name None.

We can check the type of the object using type checking in python.

The code above checks the class of stu before and after assigning None. The output is as below:

<class ‘__main__.student’>
<class ‘NoneType’>

At start stu belongs to student class but later it’s class is changed to NoneType.

One important thing to keep in mind is that there can be one and only one None object in your whole python code. Each object which is pointing to None will point to the same object.

id() is used to get the unique identifier assigned to objects in Python. As expected the above code will print the same value both of the times.

Output:

9918176

9918176

The value can be different than shown but it will print the same value for both of the statements.

What is the use of None?

None serves the purpose of NULL in other languages in Python.

  • None is used when an object is not initiated with a value.
  • None is the return type of every function which does not return anything.
  • None is returned when searched keyword is not found in dictionary.

How can we check if the given object is of type None?

The best way to check if the object is of type None is to use the is keyword.

== should not be used for checking the type of the object with None as  PEP 8 explicitly states that “comparisons to singletons like None should always be done with is or is not, never the equality operators.”

Comment down below if you have any queries related to python nonetype.

Leave a Comment

Your email address will not be published. Required fields are marked *