Index: fnmatch.py =================================================================== --- fnmatch.py (revision 82643) +++ fnmatch.py (working copy) @@ -16,6 +16,7 @@ _cache = {} # Maps text patterns to compiled regexen. _cacheb = {} # Ditto for bytes patterns. +_MAXCACHE = 100 # Maximum size of caches def fnmatch(name, pat): """Test whether FILENAME matches PATTERN. @@ -48,6 +49,8 @@ res = bytes(res_str, 'ISO-8859-1') else: res = translate(pat) + if len(cache) >= _MAXCACHE: + cache.clear() cache[pat] = regex = re.compile(res) return regex.match Index: test/test_fnmatch.py =================================================================== --- test/test_fnmatch.py (revision 82643) +++ test/test_fnmatch.py (working copy) @@ -3,7 +3,7 @@ from test import support import unittest -from fnmatch import fnmatch, fnmatchcase +from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache, _cacheb class FnmatchTestCase(unittest.TestCase): @@ -60,7 +60,24 @@ self.check_match(b'test\xff', b'te*\xff') self.check_match(b'foo\nbar', b'foo*') + def test_cache_clearing(self): + # check that caches do not grow too large + # http://bugs.python.org/issue7846 + # string pattern cache + for i in range(_MAXCACHE + 1): + fnmatch('foo', '?' * i) + + self.assertTrue(len(_cache) <= _MAXCACHE) + + # bytes pattern cache + for i in range(_MAXCACHE + 1): + fnmatch(bytes('foo', encoding='ascii'), bytes('?' * i, encoding='ascii')) + + self.assertTrue(len(_cacheb) <= _MAXCACHE) + + + def test_main(): support.run_unittest(FnmatchTestCase)