Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Chad Madden
The Python "AttributeError: 'NoneType' object has no attribute" occurs when we
try to call the group()
method on a None
value, e.g. after calling match()
or search()
with no matches. To solve the error, use an if
statement before
calling group
.
Here is a very simple example of how the error occurs.
example = None # ⛔️ AttributeError: 'NoneType' object has no attribute 'group' example.group()
Trying to access or set an attribute on a None
value causes the error.
None
, so you have to track down where the variable gets assigned a None
value and correct the assignment.The most common source of a None
value (other than an explicit assignment) is
a function that doesn't return anything.
For example, the
re.match() and
re.search methods return
None
if there are no matches.
import re # 👇️ None m = re.match(r"(\w+) (\w+)", "hello") # ⛔️ AttributeError: 'NoneType' object has no attribute 'group' print(m.group())
Since the string does not match the pattern, the match()
method returns
None
.
You can get around this by using an if
statement to check if there are matches
before calling group()
.
import re m = re.match(r"(\w+) (\w+)", "hello") if m: print(m.group()) else: print('There are no matches') # 👉️ this runs
You could also be more explicit in the if
statement and check that the m
variable is not None
.
import re m = re.match(r"(\w+) (\w+)", "hello") if m is not None: print(m.group()) else: print('There are no matches')
The re.search()
method also returns None
if no position in the string
matches the pattern.
import re # 👇️ None m = re.search('(?<=abc)def', 'xyz') # ⛔️ AttributeError: 'NoneType' object has no attribute 'group' print(m.group(0))
You can use the same approach to only call the group
method if there was a
match.
import re m = re.search('(?<=abc)def', 'abcdef') if m is not None: print(m.group()) # 👉️ def else: print('There are no matches')
The if
block is only ran if the m
variable is not None
, otherwise the
else
block runs.
The same is the case when using the Match.groups method.
import re # 👇️ none m = re.match(r"(\d+)\.(\d+)", "hello") # ⛔️ AttributeError: 'NoneType' object has no attribute 'groups' print(m.groups())
The Match.groups
method returns None
if there are no matches and a default
argument is not provided.
To get around the error, use a simple if
statement.
import re # 👇️ none m = re.match(r"(\d+)\.(\d+)", "123.456") if m is not None: print(m.groups()) # 👉️ ('123', '456') else: print('There are no matches')
The "AttributeError: 'NoneType' object has no attribute 'group'" occurs for multiple reasons:
None
implicitly).None
.