Compiling regex inside function?

Anthra Norell anthra.norell at bluewin.ch
Mon Aug 3 03:40:00 EDT 2009


Hi all,

   I have a regex that has no use outside of a particular function. From 
an encapsulation point of view it should be scoped as restrictively as 
possible. Defining it inside the function certainly works, but if 
re.compile () is run every time the function is called, it isn't such a 
good idea after all. E.g.

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?


Frederic




More information about the Python-list mailing list