1212import os
1313import posixpath
1414import re
15+ import functools
1516
16- __all__ = ["filter" , "fnmatch" , "fnmatchcase" , "purge" , "translate" ]
17-
18- _cache = {} # Maps text patterns to compiled regexen.
19- _cacheb = {} # Ditto for bytes patterns.
20- _MAXCACHE = 100 # Maximum size of caches.
21-
22-
23- def purge ():
24- """Clear the pattern cache."""
25- _cache .clear ()
26- _cacheb .clear ()
27-
17+ __all__ = ["filter" , "fnmatch" , "fnmatchcase" , "translate" ]
2818
2919def fnmatch (name , pat ):
3020 """Test whether FILENAME matches PATTERN.
@@ -45,28 +35,21 @@ def fnmatch(name, pat):
4535 pat = os .path .normcase (pat )
4636 return fnmatchcase (name , pat )
4737
48-
49- def _compile_pattern (pat ):
50- cache = _cacheb if isinstance (pat , bytes ) else _cache
51- regex = cache .get (pat )
52- if regex is None :
53- if isinstance (pat , bytes ):
54- pat_str = str (pat , 'ISO-8859-1' )
55- res_str = translate (pat_str )
56- res = bytes (res_str , 'ISO-8859-1' )
57- else :
58- res = translate (pat )
59- if len (cache ) >= _MAXCACHE :
60- cache .clear ()
61- cache [pat ] = regex = re .compile (res )
62- return regex .match
63-
38+ @functools .lru_cache (maxsize = 250 )
39+ def _compile_pattern (pat , is_bytes = False ):
40+ if is_bytes :
41+ pat_str = str (pat , 'ISO-8859-1' )
42+ res_str = translate (pat_str )
43+ res = bytes (res_str , 'ISO-8859-1' )
44+ else :
45+ res = translate (pat )
46+ return re .compile (res ).match
6447
6548def filter (names , pat ):
6649 """Return the subset of the list NAMES that match PAT."""
6750 result = []
6851 pat = os .path .normcase (pat )
69- match = _compile_pattern (pat )
52+ match = _compile_pattern (pat , isinstance ( pat , bytes ) )
7053 if os .path is posixpath :
7154 # normcase on posix is NOP. Optimize it away from the loop.
7255 for name in names :
@@ -78,14 +61,13 @@ def filter(names, pat):
7861 result .append (name )
7962 return result
8063
81-
8264def fnmatchcase (name , pat ):
8365 """Test whether FILENAME matches PATTERN, including case.
8466
8567 This is a version of fnmatch() which doesn't case-normalize
8668 its arguments.
8769 """
88- match = _compile_pattern (pat )
70+ match = _compile_pattern (pat , isinstance ( pat , bytes ) )
8971 return match (name ) is not None
9072
9173
0 commit comments