Repository navigation
Description
Bug report
fnmatch._translate() handles each [ by scanning forward for the closing ]. When there is none, the [ is emitted as a literal and the loop advances by one character, so the next [ scans to the end of the pattern again. A pattern made of many unclosed brackets therefore takes O(n²) time.
This affects fnmatch.fnmatch, fnmatchcase, filter and translate, and also glob.translate() and pathlib.PurePath.full_match(), which use the same _translate() loop. A service that lets users filter names with a glob (search boxes, include/exclude options, path-pattern ACLs) can be stalled for seconds per request with a few tens of kilobytes of input.
import fnmatch, glob, pathlib, sys, time
def t(f):
s = time.perf_counter(); f(); return time.perf_counter() - s
for n in (4000, 8000, 16000):
pat = "[!" * n
print(f"{len(pat):>6} bytes: fnmatch {t(lambda: fnmatch.fnmatch('x', pat)):6.2f}s "
f"glob.translate {t(lambda: glob.translate(pat)):6.2f}s "
f"full_match {t(lambda: pathlib.PurePosixPath('x').full_match(pat)):6.2f}s")
slow = t(lambda: fnmatch.translate("[!" * 16000)) > 1
print("QUADRATIC" if slow else "OK"); sys.exit(1 if slow else 0)Output, Python 3.15.2 on Linux (exit code 1):
8000 bytes: fnmatch 0.62s glob.translate 0.62s full_match 0.60s
16000 bytes: fnmatch 2.40s glob.translate 2.45s full_match 2.43s
32000 bytes: fnmatch 9.75s glob.translate 9.72s full_match 9.87s
QUADRATIC
Python 3.14.3 on Windows shows the same growth (32000 bytes: 12.65s / 11.77s / 11.86s).
Doubling the pattern length quadruples the time. The _translate() function on main is identical to 3.15.2.
Suggested fix
If there is no ] after the current position, the scan cannot succeed, and neither can the scan for any later [. So find the last ] once and skip the scan when we're past it:
i, n = 0, len(pat)
+ last_close = pat.rfind(']')
while i < n:
c = pat[i]
i = i+1
...
elif c == '[':
+ if i > last_close:
+ # No ']' after this point: every later '[' is a literal too.
+ add('\\[')
+ continue
j = iWhen i > last_close there is no ] at index i or later, so the existing scan would always end with j >= n and add('\\['). The fast path produces the same output. I compared translate() with and without the patch on 300,000 random patterns over the alphabet []!-^\*?ab (including backslash), and the output was identical. With the patch, a 200 KB "[!" * n pattern translates in 0.03 s (11.7 s for 32 KB before).
If a ] follows the [, the bracket is consumed up to that ], so that path was already linear overall. I can open a PR with this change and a test.
CPython versions tested on:
3.14, 3.15
Operating systems tested on:
Linux, Windows
Activity
pythongh-163137: Fix quadratic time in fnmatch.translate() for unclos…