Summary: NoneType attribute error occurs when the type of object being referenced is
None. To handle this error you can either use the
try-except blocks or you may also use if-else statements according to your requirement.
In this article, you will learn about attribute errors with the help of numerous scenarios/examples where you come across such errors and how to deal with the error. So, without further delay let us dive into our discussion.
❖ Attribute Error
Before we learn how to resolve the attribute error, it is important to understand what is an attribute error or why do we encounter an attribute error?
What is an attribute in Python?
In Python, an attribute can be considered as any property associated with a particular type of object. For example,
remove are some of the attributes of the list type object.
This brings us to the question, what is an attribute error?
Whenever you try to reference an invalid attribute, you get an "attribute error".
In other words, attribute errors are raised when you try to access a certain attribute of a particular object, however, the object does not possess the called attribute. Let us understand this with reference to our previous example of the list tye object. Since
insert is an attribute of the list type object, we will face no issues while using
insert with a list. However, a tuple does not possess the
insert attribute. Hence, if you try to reference the
insert attribute with respect to a tuple, you will get an attribute error.
tup = ("Square", "Rectangle", "Pentagon") tup.insert(2,'circle') print(tup)
AttributeError: 'tuple' object has no attribute 'insert'
This brings us to the next phase of our discussion where we will discuss ‘NoneType’ object has no attribute ‘xyz’ error.
❖ ‘NoneType’ Object Has No Attribute ‘xyz’
There may be cases where you encounter an error that says:
AttributeError: 'NoneType' object has no attribute 'something'
Let us try to dissect our problem and understand the scenarios which can cause such
So, what is
NoneType supposed to mean?
NoneType means that whatever class or object you are trying to access is
None. Therefore, whenever there is a function call or an assignment with regards to that object, it will fail or return an unexpected output.
You may encounter such an
attribute error in numerous scenarios. Let us have a look at some scenarios where you may come across such an error.
✨ Scenario 1
x1 = None print(x1.something)
File "D:/PycharmProjects/Errors/attribute_error.py", line 2, in <module> print(x1.something) AttributeError: 'NoneType' object has no attribute 'something'
✨ Scenario 2
x1 = None x1.some_attribute = "Finxter"
Traceback (most recent call last): File "D:/PycharmProjects/Errors/attribute_error.py", line 2, in <module> x1.some_attribute = "FINXTER" AttributeError: 'NoneType' object has no attribute 'some_attribute'
✨ Scenario 3
def foo(a): if a < 0: return a y = foo(5) print(y.func())
Traceback (most recent call last): File "D:/PycharmProjects/Errors/attribute_error.py", line 7, in <module> print(y.func()) AttributeError: 'NoneType' object has no attribute 'func'
Explanation: In the above code, the function call is not returning anything or in other words, it is returning
None and we are trying to access a non-existing attribute of that
None type object.
✨ Solution 1 : Use if-else Statements
To avoid the
NoneType attribute error you can use the if-else statements accordingly to eliminate or skip the situation where the returned object type is
x1 = None if x1 is not None: x1.some_attribute = "Finxter" else: print("The type of x1 is ", type(x1))
The type of x1 is <class 'NoneType'>
✨ Solution 2 : Use try-except blocks (Exception Handling)
Another workaround to deal with an attribute error is to use exception handling i.e. the
def foo(a): if a < 0: return a x = foo(-1) y = foo(5) try: print(x) print(y.func()) # Raises an AttributeError except AttributeError: print("No such Attribute!")
-1 No such Attribute!
❖ How To Fix Error: ‘NoneType’ Object Has No Attribute ‘Group’?
Since we have already discussed the reasons for getting a
NoneType attribute error and the ways to handle such errors, let us have a look at a very commonly asked question based on our earlier discussion.
🔔 AttributeError: ‘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())
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
None. Hence, when we try to use the attribute for the
NoneType object, it returns an attribute error.
group() for the situation where
None and thus does not match the Regex. Therefore use the
try-except block such that the attribute error is handled by the except block. The following code will further clarify things:
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
Note: The above example deals with regex. Do you want to master the regex superpower? Check out our book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
The key areas covered in this article were:
- What is an
- What is a
- The scenarios when we encounter attribute errors.
- Methods to deal with attribute error:
- using if-else
- using try-except
- How To Fix Error: ‘NoneType’ Object Has No Attribute ‘Group’?
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.