[FIXED] AttributeError: ‘NoneType’ object has no attribute ‘something’

Introduction

Problem: How to solve “AttributeError: ‘NoneType’ object has no attribute ‘something’ “?

An AttributeError is raised in Python when you attempt to call the attribute of an object whose type does not support the method. For example, attempting to utilize the append() method on a string returns an AttributeError as lists use the append() function and strings don’t support it.Ā 

Example:

# A set of strings
names = {"John", "Rashi"}
names.extend("Chris")
print(names)

Output:

Traceback (most recent call last):
  File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxer\Errors\AttributeError - None Type Object.py", line 3, in <module>
    names.extend("Chris")
AttributeError: 'set' object has no attribute 'extend'

Hence, if you attempt to reference a value or function not related to a class object or data type, it will raise an AttributeError.

AttributeError:’NoneType’ object has no attribute ‘something’

Different reasons raise AttributeError: 'NoneType' object has no attribute 'something'. One of the reasons is that NoneType implies that instead of an instance of whatever Class or Object that you are working with, in reality, you have got None. It implies that the function or the assignment call has failed or returned an unforeseen outcome.Ā 

Let’s have a look at an example that leads to the occurrence of this error.

Example 1:

# Assigning value to the variable 
a = None
print(a.something)

Output:

Traceback (most recent call last):
  File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxer\Errors\AttributeError - None Type Object.py", line 3, in <module>
    print(a.something)
AttributeError: 'NoneType' object has no attribute 'something'

Hence, AttributeError: ‘NoneType’ object has no attribute ‘something’ error occurs when the type of object you are referencing is None.Ā  It can also occur when you reference a wrong function instead of the function used in the program.

Example:

# A function to print numbers
def fun(x):
    if x <= 10:
        x = x + 1
    return x


a = fun(5)
# Calling the function that does not exist
print(a.foo())

Output:

Traceback (most recent call last):
  File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxer\Errors\AttributeError - None Type Object.py", line 10, in <module>
    print(a.foo())
AttributeError: 'int' object has no attribute 'foo'

How to check if the operator is Nonetype?

Since this AttributeError revolves around the NoneType object, hence it is of primary importance to identify if the object referred has a type None. Thus, you can check if the operator is Nonetype with the help of the “is” operator. It will return True if the object is of the NoneType and return False if not.

Example:

x = None
if x is None:
    print("The value is assigned to None")
else:
    print(x)

Output:

The value is assigned to None

Now that you know how AttributeError: ‘NoneType’ object has no attribute ‘something’ gets raised let’s look at the different methods to solve it.

#Fix 1: Using if and else statements

You can eliminate the AttributeError: 'NoneType' object has no attribute 'something' by using the- if and else statements. The idea here is to check if the object has been assigned a None value.Ā  If it is None then just print a statement stating that the value is Nonetype which might hamper the execution of the program.

Example:

x1 = None
if x1 is not None:
    x1.some_attribute = "Finxter"
else:
    print("The type of x1 is ", type(x1))

Output:

The type of x1 is  <class 'NoneType'>

#Fix 2: Using try and except Blocks

You can also use the exception handling (try and except block) to solve the AttributeError: 'NoneType' object has no attribute 'something'.

Example:

# A function to print numbers
def fun(x):
    if x <= 10:
        x = x + 1
    return x


a = fun(5)
# Using exception handling (try and except block)
try:
    print(a)
    # Calling the function that does not exist
    print(a.foo())

except AttributeError as e:
    print("The value assigned to the object is Nonetype")

Output:

6
The value assigned to the object is Nonetype

Quick Review

Now that we have gone through the ways to fix this AttributeError, let’s go ahead and visualize a few other situations which lead to the occurrence of similar attribute errors and then solve them using the methods we learned above.

1. ā€˜NoneTypeā€™ Object Has No Attribute ā€˜Groupā€™

import re
# Search for an upper case "S" character in the beginning of a word, and print the word:
txt = "The rain in Spain"
for i in txt.split():
    x = re.match(r"\bS\w+", i)
    print(x.group())

Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/Errors/attribute_error.py", line 9, in <module>
    print(x.group())
AttributeError: 'NoneType' object has no attribute 'group'

The code encounters an attribute error because in the first iteration it cannot find a match, therefore x returns None. Hence, when we try to use the attribute for the NoneType object, it returns an attribute error.

Solution: NeglectĀ group()Ā for the situation whereĀ xĀ returnsĀ NoneĀ and thus does not match the Regex. Therefore use theĀ try-exceptĀ blocks such that the attribute error is handled by the except block.Ā 

import re
txt = "The rain in Spain"
for i in txt.split():
    x = re.match(r"\bS\w+", i)
    try:
        print(x.group())
    except AttributeError:
        continue

# Output : Spain

2. Appending list But error ‘NoneType’ object has no attribute ‘append’

li = [1, 2, 3, 4]
for i in range(5):
    li = li.append(i)
print(li)

Output:

Traceback (most recent call last):
  File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxer\Errors\AttributeError - None Type Object.py", line 3, in <module>
    li = li.append(i)
AttributeError: 'NoneType' object has no attribute 'append'

Solution:

When you are appending to the list asĀ i = li.append(i)Ā you are trying to do an inplace operation which modifies the object and returns nothing (i.e.Ā None). In simple words, you should not assign the value to the li variable while appending, it updates automatically.Ā This is how it should be done:

li = [1, 2, 3, 4]
for i in range(5):
    li.append(i)
print(li)

# output: [1, 2, 3, 4, 0, 1, 2, 3, 4]

Conclusion

To sum things up, there can be numerous cases wherein you wil encounter an attribute error of the above type. But the underlying reason behind every scenario is the same, i.e., theĀ typeĀ of object being referenced isĀ None. To handle this error, you can try to rectify the root of the problem by ensuring that the object being referenced is not None. You may also choose to bypass the error based on the requirement of your code with the help of try-cath blocks.

I hope this article helped you to gain a deep understanding ofĀ attribute errors. PleaseĀ stay tunedĀ andĀ subscribeĀ for more interesting articles and discussions.


To become a PyCharm master, check out our full course on the Finxter Computer Science Academy available for free for all Finxter Premium Members: