AppDividend
Latest Code Tutorials

Python Null Example | None in Python Demystified

0

Python Null object is the singleton None. There’s no null value in Python; instead, there’s None. The equivalent of the null keyword in Python is None. Many would argue that the word “null” is somewhat esoteric. It’s not exactly the friendliest word to programming novices.  Also, “None” refers precisely to the intended functionality – it is nothing, and has no behavior.  In Python, None is the object and first-class citizen!

History of Null

Many programming languages use Null to represent a pointer that doesn’t point to anything, its kind of placeholder when a variable is empty, or to mark default parameters that you haven’t supplied yet. The Null is often defined to be 0 in those languages, but Null in Python is different.

In most object-oriented languages, the naming of objects tends to use camel-case syntax. Eg. ThisIsMyObject. As you’ll see soon, Python’s None type is an object and behaves like one.

As stated already, the most accurate way to test that something has been given None as the value is to use the is identity operator, which tests that two variables refer to the same object.

In other programming languages, for example, this is how you may create a null variable in PHP and Java. Let’s see how other Java and PHP define a Null variable.

Null In Java

myVariable = null;

Null In PHP

$myVariable = NULL;

If you need to evaluate a variable in the if condition, you may check this as follows in Java:

if(myVariable == null) {
  System.out.println(”Some output”);
}

How to use the ‘None’ in Python. I will use it in the if statement and a few compound data types.

Understanding None in Python

If you define a function that has a return statement or returns no value, then it returns None.

def python_none():
    pass


print(python_none())

Output

None

When you call python_none() function, it returns None because there is no return statement. There is only a pass statement.

None by itself has no output value, but printing it shows None to the Python console that we are forcing explicitly to print the output.

None indicates missing or default parameters. For example, None appears twice in the docs for list.sort.

print(help(list.sort))

Output

sort(self, /, *, key=None, reverse=False)
    Sort the list in ascending order and return None.

    The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
    order of two equal elements is maintained).

    If a key function is given, apply it once to each list item and sort them,
    ascending or descending, according to their function values.

    The reverse flag can be set to sort in descending order.

In the output, you can see that the parameter key has None value. That means the key parameter is required, but we have not provided; that is why the default parameter is None.

Proof that None is Object

None is the singleton and the NoneType class only gives you the same single instance of None. There’s only one None in our Python program.

NoneObj = type(None)()
print(NoneObj)

# Check if NoneObj is instance of NoneType class
print(NoneObj is None)

It gives the following output.

None
True

 Even though you try to create the new instance, you still get existing None.

Interesting Facts about None

  1. None is not the same as False.
  2. None is not an empty string.
  3. None is not 0.
  4. Comparing None to anything will always return False except None itself.

Declaring None in Python

We can assign None object to any variable at the time of declaration. Python variables come to life by assignment operator, which helps us to assign the particular value to the variable. In some programming languages, they don’t have to have an initial value assigned to them. The initial value for some types of variables might be Null

Let’s assign the None value to a variable in Python and print the variable in the console.

data = None
print(None)

Output

None

 If we don’t define a variable and direct print its value, then we will get NameError.

print(data)

Output

Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(data)
NameError: name 'data' is not defined

All variables in Python come into life by the assignment operator. A variable can only start life as Null if you assign None to it. If you don’t define a variable and directly try to print in the console, then you will get NameError.

Using None as part of a comparison

There’s no null in Python. Instead, there’s None. As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

In Python, to represent an absence of the value, you can use a None value (types.NoneType.None) for objects and “” (or len() == 0) for strings.

Regarding the difference between “==” and “is,” testing for object identity using “==” should be sufficient.

However, since the operation “is” is defined as an object identity operation, it is probably more correct to use it, rather than “==”. Not sure if there is even the speed difference.

An essential rule of thumb keeps in mind when you are checking for None values.

  1. Do use identity operators is and is not.
  2. Do not use the equality operators == and !=.

The difference between == and Python is Operator.

Difference between == and is operator in Python is that == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not. 

See the following code.

# app.py

eleven = None
print(eleven is None)

See the following output.

➜  pyt python3 app.py
True
➜  pyt

Now, see the following code.

def python_none():
    pass


data = python_none()
print(data == None)
print(data is None)

Output

True
True

In this code, it returns None, and we check in both ways that data is indeed None.

But, The equality operators can be fooled when you’re comparing user-defined objects that override them.

class isAndDoubleEqual:
    def __eq__(self, other):
        return True


res = isAndDoubleEqual()
print(res == None)
print(res is None)

Output

True
False

The equality operator == returns the incorrect answer.

The identity “is operator” returns the correct answer because it can’t be fooled because you can’t override it.

Checking type of None

In other programming languages, Null is just a synonym for 0, but Null in Python is an object.

Check the type of None using type() method.

print(type(None))

Output

<class 'NoneType'>

This shows that None is the object, and its data type is NoneType.

None by itself is built into the language as the Null in Python. You can check out by printing the dir(__builtins__).

print(dir(__builtins__))

 It will print the following inbuilt items.

['ArithmeticError',..., None,....., zip

Using None as a Value in Python

In Python, we can pass None as a function parameter and add as an item to the list. To do that, first, we will define a class, and we don’t define its body. Then, we create a function called list_function(), and it takes two parameters.

  1. new_item: This is the item that will be added to the list if we pass at the time of calling the function.
  2. initial_list: As a default parameter, the list should be None, but if we pass any argument explicitly, then it will return the initial list.
class DoAppendNone:
    pass


def list_function(new_item=DoAppendNone, initial_list=None):
    if initial_list is None:
        initial_list = []
    if new_item is not DoAppendNone:
        initial_list.append(new_item)
    return initial_list


data = [1, 2, 3, 4, 5]
print(list_function(initial_list=data))

Output

[1, 2, 3, 4, 5]

We have passed two parameters with its default value of the list_function(). 

  1. new_item = DoAppendNone
  2. initial_list = None

In the code, we have passed the initial_list as data because we have a data list that has five elements.

So, at the time of calling the function, our initial_list = data.

That means, inside the function, we have checked if the initial_list is None or not, but it is not None as we have a list of items in data so that that condition will be False.

The second condition is that new_element should not be DoAppendNone, but it is. So that condition will be False also. So, no new element will be added to the list.

Finally, the provided data list will be returned as an output.

Now, what if None is a valid input object? For instance, what if list_function() could either insert an item to the list or not, and None was a valid element to append? In this case, you can define the class specifically for use as a default, while being distinct from None.

So, let’s write a program that inserts a None value as an element to the list.

class DoAppendNone:
    pass


def list_function(new_item=DoAppendNone, initial_list=None):
    if initial_list is None:
        initial_list = []
    if new_item is not DoAppendNone:
        initial_list.append(new_item)
    return initial_list


data = [1, 2, 3, 4, 5]
print(list_function(None, data))

Output

[1, 2, 3, 4, 5, None]

Here, the class DoAppendNone serves as a signal not to append, so you don’t want None for that. That frees us to insert None whenever you want.

Checking None using if…else condition.

We can write the following code if we want to check if the value is None.

# app.py

value = None

if value is None:
    print('The value is null')
else:
    print('The value is not null')

In the above example, we have defined the variable called value and assigns the None value.

Then, we have used the if…else condition to check the None value, and if it does, then return print statement with “The value is null.”

We can use the following code if we want to check if the name exists.

try:
    val
except NameError:
    pass  # val does not exist at all

There can be only one None in Python.

The None is the inbuilt constant, as soon as you start Python, whether in module, class, or function. The NonType, by contrast, is not, you’d need to get a reference to it first by querying None for its class.

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

None can not be overwritten.

Before Python 2.4, it was possible to reassign None, but not anymore. Not even as the class attribute or in the confines of a function.

Checking if the value is None

Why do this

value is None

rather than

value==None

The first is equivalent to:

id(value)==id(None)

Whereas the expression value==None is applied like this

value.__eq(None)__

if the value is None, then you’ll get what you expected.

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

None has a distinctive status in Python language. It’s a preferred baseline value because many algorithms treat it as an exceptional value.

In such scenarios, it can be used as the flag to signal that the condition requires some special handling, such as the setting of the default value.

None in Tracebacks

When NoneType appears in your traceback, it means that something you didn’t expect to be None was None, and you tried to use it in a way that you can’t use None. Almost always, it’s because you’re trying to call a method on it.

data = [1, 2, 3, 4, 5]

data.append(6)
print(data)

data = None
data.append(11)
print(data)

Output

[1, 2, 3, 4, 5, 6]
Traceback (most recent call last):
  File "app.py", line 7, in <module>
    data.append(11)
AttributeError: 'NoneType' object has no attribute 'append'

When we have defined a list with some initial values, then it can call th list.append() function to add an element to the list, but when we define a list to None that means, now that list is not traditional Python list, that list is now None, and None object does not have an append() method to work with that is why it throws an AttributeError.

When you see a traceback like the above in your code, look for the attribute that raised the error first. Here, it is an append() method. From there, you’ll see the object you tried to call it on. Finally, figure out how that object got to be None and take the necessary steps to fix your code.

Conclusion

None in Python is an immutable keyword and powerful tool like True or False. None can be tested using in or not in operators. In tracebacks, None can be helpful to find the exact problem and we can fix it by solving the Null issue. In any Python program, there can be only one None, even if you create an instance of NoneType class, there can only be one None.

Finally, Python Null or None Example is over.

Recommended Posts

Python Not Equal Operator

Python Absolute Value

Python sqrt()

Python stddev()

Python variance()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.