Skip to content

Commit 4142961

Browse files
bpo-39394: Improve warning message in the re module (GH-31988)
A warning about inline flags not at the start of the regular expression now contains the position of the flag.
1 parent 0a8b8e0 commit 4142961

File tree

3 files changed

+11
-4
lines changed

3 files changed

+11
-4
lines changed

Lib/sre_parse.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -807,9 +807,11 @@ def _parse(source, state, verbose, nested, first=False):
807807
if not first or subpattern:
808808
import warnings
809809
warnings.warn(
810-
'Flags not at the start of the expression %r%s' % (
810+
'Flags not at the start of the expression %r%s'
811+
' but at position %d' % (
811812
source.string[:20], # truncate long regexes
812813
' (truncated)' if len(source.string) > 20 else '',
814+
start,
813815
),
814816
DeprecationWarning, stacklevel=nested + 6
815817
)

Lib/test/test_re.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1444,7 +1444,8 @@ def test_inline_flags(self):
14441444
self.assertTrue(re.match(p, lower_char))
14451445
self.assertEqual(
14461446
str(warns.warnings[0].message),
1447-
'Flags not at the start of the expression %r' % p
1447+
'Flags not at the start of the expression %r'
1448+
' but at position 1' % p
14481449
)
14491450
self.assertEqual(warns.warnings[0].filename, __file__)
14501451

@@ -1453,7 +1454,8 @@ def test_inline_flags(self):
14531454
self.assertTrue(re.match(p, lower_char))
14541455
self.assertEqual(
14551456
str(warns.warnings[0].message),
1456-
'Flags not at the start of the expression %r (truncated)' % p[:20]
1457+
'Flags not at the start of the expression %r (truncated)'
1458+
' but at position 1' % p[:20]
14571459
)
14581460
self.assertEqual(warns.warnings[0].filename, __file__)
14591461

@@ -1465,7 +1467,8 @@ def test_inline_flags(self):
14651467
self.assertTrue(re.match(p, b'a'))
14661468
self.assertEqual(
14671469
str(warns.warnings[0].message),
1468-
'Flags not at the start of the expression %r' % p
1470+
'Flags not at the start of the expression %r'
1471+
' but at position 1' % p
14691472
)
14701473
self.assertEqual(warns.warnings[0].filename, __file__)
14711474

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
A warning about inline flags not at the start of the regular expression now
2+
contains the position of the flag.

0 commit comments

Comments
 (0)