Regex recompiled in loop (ARCH2073)
Key python.performance.regex-recompiled-in-loop · Severity info · Category performance
Compiling a constant pattern on every loop iteration is wasteful. Compile the pattern once with re.compile outside the loop and reuse it.
Incorrect
Section titled “Incorrect”import re
def find_codes(lines): out = [] for line in lines: if re.match(r"^[A-Z]{3}\d{4}$", line): out.append(line) return outCorrect
Section titled “Correct”import re
CODE_RE = re.compile(r"^[A-Z]{3}\d{4}$")
def find_codes(lines): return [line for line in lines if CODE_RE.match(line)]Compile the constant pattern once at module level with re.compile outside the loop.