Skip to content

Commit 114454e

Browse files
bpo-28293: Don't completely dump the regex cache when full. (#3768)
1 parent 0e950dd commit 114454e

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

Lib/re.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,13 @@
128128
except ImportError:
129129
_locale = None
130130

131+
# try _collections first to reduce startup cost
132+
try:
133+
from _collections import OrderedDict
134+
except ImportError:
135+
from collections import OrderedDict
136+
137+
131138
# public symbols
132139
__all__ = [
133140
"match", "fullmatch", "search", "sub", "subn", "split",
@@ -260,7 +267,7 @@ def escape(pattern):
260267
# --------------------------------------------------------------------
261268
# internals
262269

263-
_cache = {}
270+
_cache = OrderedDict()
264271

265272
_pattern_type = type(sre_compile.compile("", 0))
266273

@@ -281,7 +288,10 @@ def _compile(pattern, flags):
281288
p = sre_compile.compile(pattern, flags)
282289
if not (flags & DEBUG):
283290
if len(_cache) >= _MAXCACHE:
284-
_cache.clear()
291+
try:
292+
_cache.popitem(False)
293+
except KeyError:
294+
pass
285295
_cache[type(pattern), pattern, flags] = p
286296
return p
287297

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The regular expression cache is no longer completely dumped when it is full.

0 commit comments

Comments
 (0)