Compiling regex inside function?
Anthra Norell
anthra.norell at bluewin.ch
Tue Aug 4 04:02:31 EDT 2009
alex23 wrote:
> Anthra Norell <anthra.nor... at bluewin.ch> wrote:
>
>> def entries (l):
>> r = re.compile ('([0-9]+) entr(y|ies)')
>> match = r.search (l)
>> if match: return match.group (1)
>>
>> So the question is: does "r" get regex-compiled once at py-compile time
>> or repeatedly at entries() run time?
>>
> The docs say:
> The compiled versions of the most recent patterns passed to re.match
> (), re.search() or re.compile() are cached, so programs that use only
> a few regular expressions at a time needn’t worry about compiling
> regular expressions.
>
> (But they don't say how few is 'only a few'...)
>
> If you're concerned about it, you could always set the compiled
> pattern to a default value in the function's argspec, as that _is_
> only executed the once:
>
> def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'):
> match = regex.search(line)
> ...
>
Excellent idea! Thank you all for the tips.
Frederic
More information about the Python-list
mailing list