Can I rely on...

alex23 wuwei23 at gmail.com
Thu Mar 19 22:41:08 EDT 2009


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.")



More information about the Python-list mailing list