Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ea340a3

Browse files
committed
7846: limit fnmatch pattern cache to _MAXCACHE=100 entries.
Patch by Andrew Clegg.
1 parent facb0e9 commit ea340a3

4 files changed

Lines changed: 22 additions & 1 deletion

File tree

Lib/fnmatch.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
_cache = {} # Maps text patterns to compiled regexen.
1818
_cacheb = {} # Ditto for bytes patterns.
19+
_MAXCACHE = 100 # Maximum size of caches
1920

2021
def fnmatch(name, pat):
2122
"""Test whether FILENAME matches PATTERN.
@@ -48,6 +49,8 @@ def _compile_pattern(pat):
4849
res = bytes(res_str, 'ISO-8859-1')
4950
else:
5051
res = translate(pat)
52+
if len(cache) >= _MAXCACHE:
53+
cache.clear()
5154
cache[pat] = regex = re.compile(res)
5255
return regex.match
5356

Lib/test/test_fnmatch.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from test import support
44
import unittest
55

6-
from fnmatch import fnmatch, fnmatchcase
6+
from fnmatch import fnmatch, fnmatchcase, _MAXCACHE, _cache, _cacheb
77

88

99
class FnmatchTestCase(unittest.TestCase):
@@ -60,6 +60,21 @@ def test_bytes(self):
6060
self.check_match(b'test\xff', b'te*\xff')
6161
self.check_match(b'foo\nbar', b'foo*')
6262

63+
def test_cache_clearing(self):
64+
# check that caches do not grow too large
65+
# http://bugs.python.org/issue7846
66+
67+
# string pattern cache
68+
for i in range(_MAXCACHE + 1):
69+
fnmatch('foo', '?' * i)
70+
71+
self.assertLessEqual(len(_cache), _MAXCACHE)
72+
73+
# bytes pattern cache
74+
for i in range(_MAXCACHE + 1):
75+
fnmatch(b'foo', b'?' * i)
76+
self.assertLessEqual(len(_cacheb), _MAXCACHE)
77+
6378

6479
def test_main():
6580
support.run_unittest(FnmatchTestCase)

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ Vadim Chugunov
146146
David Cinege
147147
Mike Clarkson
148148
Brad Clements
149+
Andrew Clegg
149150
Steve Clift
150151
Nick Coghlan
151152
Josh Cogliati

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,8 @@ C-API
470470
Library
471471
-------
472472

473+
- Issue #7646: The fnmatch pattern cache no longer grows without bound.
474+
473475
- Issue #9136: Fix 'dictionary changed size during iteration'
474476
RuntimeError produced when profiling the decimal module. This was
475477
due to a dangerous iteration over 'locals()' in Context.__init__.

0 commit comments

Comments
 (0)