Skip to content

Commit 6ccfa31

Browse files
gh-90568: Fix exception type for \N with a named sequence in RE (GH-91665)
re.error is now raised instead of TypeError.
1 parent 2f233fc commit 6ccfa31

File tree

3 files changed

+9
-2
lines changed

3 files changed

+9
-2
lines changed

Lib/re/_parser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ def _class_escape(source, escape):
333333
charname = source.getuntil('}', 'character name')
334334
try:
335335
c = ord(unicodedata.lookup(charname))
336-
except KeyError:
336+
except (KeyError, TypeError):
337337
raise source.error("undefined character name %r" % charname,
338338
len(charname) + len(r'\N{}')) from None
339339
return LITERAL, c
@@ -393,7 +393,7 @@ def _escape(source, escape, state):
393393
charname = source.getuntil('}', 'character name')
394394
try:
395395
c = ord(unicodedata.lookup(charname))
396-
except KeyError:
396+
except (KeyError, TypeError):
397397
raise source.error("undefined character name %r" % charname,
398398
len(charname) + len(r'\N{}')) from None
399399
return LITERAL, c

Lib/test/test_re.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -772,6 +772,10 @@ def test_named_unicode_escapes(self):
772772
"undefined character name 'SPAM'", 0)
773773
self.checkPatternError(r'[\N{SPAM}]',
774774
"undefined character name 'SPAM'", 1)
775+
self.checkPatternError(r'\N{KEYCAP NUMBER SIGN}',
776+
"undefined character name 'KEYCAP NUMBER SIGN'", 0)
777+
self.checkPatternError(r'[\N{KEYCAP NUMBER SIGN}]',
778+
"undefined character name 'KEYCAP NUMBER SIGN'", 1)
775779
self.checkPatternError(br'\N{LESS-THAN SIGN}', r'bad escape \N', 0)
776780
self.checkPatternError(br'[\N{LESS-THAN SIGN}]', r'bad escape \N', 1)
777781

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Parsing ``\N`` escapes of Unicode Named Character Sequences in a
2+
:mod:`regular expression <re>` raises now :exc:`re.error` instead of
3+
``TypeError``.

0 commit comments

Comments
 (0)