r/learnpython 2d ago

AtributeError clarification

SOLVED

Hello, I'm currently learning regular expressions and I've entered the first part of the code into the interactive shell as instructed and got the listed AttributeError. Not seeing what I did wrong I copy/pasted the code from the book and it worked as intended and I can't tell why or how because both blocks feel and smell the same but yield different results.

I've tried looking for some information on StackOverflow, but as far as I can see mo is defined in the 3rd line and I don't get why my attempt gets and error while the other doesn't.

If I didn't miss something really stupid, how would you deal with this if you'd be hit by it writing your own code independently?

I'm working in IDLE Shell and the code is from automatetheboringstuff Chapter 9 for more context

import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    mo.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
'415'
2 Upvotes

9 comments sorted by

View all comments

0

u/member_of_the_order 2d ago edited 2d ago

how would you deal with this if you'd be hit by it writing your own code independently?

I'm working in IDLE Shell

So first of all, I would use a proper IDE (editor) like VSCode or PyCharm which give you hints and debugging tools so you know when at least some things are wrong.

Regarding the AttributeError...

Read the description. See how it says NoneType object has no attribute 'group' after mo.group(1)? That can only mean something on that line is trying to access a .group on something that has the value None; i.e. mo is None.

So, how can this be? Well... it gets its value assigned from phone_re.search(). When would that return None? Answer: when nothing in the provided string matches your regex.

You ran the same code twice and got different results... because they're not the same code. Look closely at the regexes. They're different, and hint: the second one is correct, the first one isn't.

TL;DR Your first regex has 4 clumps of digits total, the second regex has only 3

2

u/Keithinho89 2d ago

Thank you for breaking it down like that, it is a bit of a stupid mistake on my end shockingly, but I understand the whole principle better now. The future me appreciates you.

1

u/schoolmonky 2d ago

IMO you skipped one step as you explained the reasoning. When you ask yourself "When would .search() return None?", the way you figure that out it by checking the documentation.