Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Lib/re.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,8 @@ def _compile(pattern, flags):
# internal: compile pattern
if isinstance(flags, RegexFlag):
flags = flags.value
elif not isinstance(flags, int):
raise TypeError(f"flags must be int or RegexFlag, got {flags!r}")
try:
return _cache[type(pattern), pattern, flags]
except KeyError:
Expand Down
17 changes: 17 additions & 0 deletions Lib/test/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -1967,6 +1967,23 @@ def test_bug_29444(self):
self.assertEqual(m.group(), b'xyz')
self.assertEqual(m2.group(), b'')

def test_compile_cache_type(self):
# bpo-31671: Make sure that re.compile() cache checks the flags type

# Make sure that float flags is invalid when the cache is empty
re.purge()
with self.assertRaises(TypeError):
re.compile("abc", flags=float(re.IGNORECASE))

# Make sure that float flags is still seen as invalid
# when the cache is full: the cache must handle flags type
re.purge()
pattern1 = re.compile("abc", flags=re.IGNORECASE)
pattern2 = re.compile("abc", flags=int(re.IGNORECASE))
self.assertEqual(pattern1, pattern2)
with self.assertRaises(TypeError):
re.compile("abc", flags=float(re.IGNORECASE))


class PatternReprTests(unittest.TestCase):
def check(self, pattern, expected):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
re.compile() cache now checks the flags type. Make sure that float flags are
rejected even if the cache has an entry with equal flags but flags of a
different type.