I'm optimizing a project at work, and during profiling I found out that most of the time is spent compiling regexes on-the-fly and matching patterns.
I'm planning on pre-compiling regexes to save execution time, but I don't know where I should declare or store them. Here's a sample of the current code:
def is_specific_stuff(line):
expr = ".*(specific|work)_stuff.*"
match = re.match(expr, line)
return bool(match)
And the code I would like to write:
def is_specific_stuff(line):
expr = re.compile('.*(specific|work)_stuff.*')
return expr.match(line) is not None
However, I don't know how I should handle expr = re.compile(...)
. Where can I store the compiled regex without making it a module-wide constant (we have several different regexes, and I would like to keep it somewhat close to the code that needs it for readability), and without recreating it with each call?
Thank you