Compiling regex inside function?

alex23 wuwei23 at
Mon Aug 3 18:56:02 CEST 2009

Anthra Norell <anthra.nor... at> wrote:
> def entries (l):
>         r = re.compile ('([0-9]+) entr(y|ies)')
>         match = (l)
>         if match: return (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
(), 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 =

More information about the Python-list mailing list