diff --git a/Lib/re.py b/Lib/re.py --- a/Lib/re.py +++ b/Lib/re.py @@ -122,6 +122,7 @@ import enum import sre_compile import sre_parse +import functools try: import _locale except ImportError: @@ -231,11 +232,6 @@ "Compile a regular expression pattern, returning a pattern object." return _compile(pattern, flags) -def purge(): - "Clear the regular expression caches" - _cache.clear() - _cache_repl.clear() - def template(pattern, flags=0): "Compile a template pattern, returning a pattern object" return _compile(pattern, flags|T) @@ -278,7 +274,6 @@ # internals _cache = {} -_cache_repl = {} _pattern_type = type(sre_compile.compile("", 0)) @@ -311,17 +306,10 @@ _cache[type(pattern), pattern, flags] = p, loc return p +@functools.lru_cache(_MAXCACHE) def _compile_repl(repl, pattern): # internal: compile replacement pattern - try: - return _cache_repl[repl, pattern] - except KeyError: - pass - p = sre_parse.parse_template(repl, pattern) - if len(_cache_repl) >= _MAXCACHE: - _cache_repl.clear() - _cache_repl[repl, pattern] = p - return p + return sre_parse.parse_template(repl, pattern) def _expand(pattern, match, template): # internal: match.expand implementation hook @@ -338,6 +326,11 @@ return sre_parse.expand_template(template, match) return filter +def purge(): + "Clear the regular expression caches" + _cache.clear() + _compile_repl.cache_clear() + # register myself for pickling import copyreg