bpo-28293: Don't completely dump the regex cache when full. (#3768) · python/cpython@114454e (original) (raw)

Original file line number Diff line number Diff line change
@@ -128,6 +128,13 @@
128 128 except ImportError:
129 129 _locale = None
130 130
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 +
131 138 # public symbols
132 139 __all__ = [
133 140 "match", "fullmatch", "search", "sub", "subn", "split",
@@ -260,7 +267,7 @@ def escape(pattern):
260 267 # --------------------------------------------------------------------
261 268 # internals
262 269
263 -_cache = {}
270 +_cache = OrderedDict()
264 271
265 272 _pattern_type = type(sre_compile.compile("", 0))
266 273
@@ -281,7 +288,10 @@ def _compile(pattern, flags):
281 288 p = sre_compile.compile(pattern, flags)
282 289 if not (flags & DEBUG):
283 290 if len(_cache) >= _MAXCACHE:
284 -_cache.clear()
291 +try:
292 +_cache.popitem(False)
293 +except KeyError:
294 +pass
285 295 _cache[type(pattern), pattern, flags] = p
286 296 return p
287 297