Can I rely on...

R. David Murray rdmurray at bitdance.com
Fri Mar 20 07:56:40 EDT 2009


alex23 <wuwei23 at gmail.com> wrote:
> On Mar 20, 1:42 am, "Emanuele D'Arrigo" <man... at gmail.com> wrote:
> > I just had a bit of a shiver for something I'm doing often in my code
> > but that might be based on a wrong assumption on my part. Take the
> > following code:
> >
> > pattern = "aPattern"
> >
> > compiledPatterns = [ ]
> > compiledPatterns.append(re.compile(pattern))
> >
> > if(re.compile(pattern) in compiledPatterns):
> >     print("The compiled pattern is stored.")
> 
> Others have discussed the problem with relying on the compiled RE
> objects being the same, but one option may be to use a dict instead of
> a list and matching on the pattern string itself:
> 
> compiledPatterns = { }
> if pattern not in compiledPatterns:
>     compiledPatterns[pattern] = re.compile(pattern)
> else:
>     print("The compiled pattern is stored.")

FYI this is almost exactly the approach the re module takes to
caching the expressions.  (The difference is re adds a type
token to the front of the key.)

--
R. David Murray           http://www.bitdance.com




More information about the Python-list mailing list