re compiled object result caching?

Dan thermostat at gmail.com
Wed Aug 29 15:51:41 EDT 2007


I find myself often using regular expressions in the following
pattern:

foo_re = re.compile(r"foo(bar)")
# . . .
re_result = foo_re.search(line)
if re_result:
    bar = re_result.group(1)
    # . . .

But, I keep thinking this is awkward, and I would kind of like to have
the re object to cache its result; along the lines of:

foo_re = re.compile(r"foo(bar)")
# . . .
if foo_re.search(line):
    foo_re.last_result().group(1)

I realize I could do this with a wrapper object (I'm not sure if I can
subclass the re object..), but I was wondering what the community
thought of this. Good idea? Bad? Would it be difficult to add to the
standard re module? The only real downside I can think of is thread
safety. The other practical benefit I can think of is situations like
the following:

if unlikely_condition and foo_re.search(line):
   # . . .

With the current implementation I think you would either have to do
the search even if unlikely_condition is False, or you would have to
do an annoying nested if. Is there another way to achieve this that
I'm not thinking of?

-Dan




More information about the Python-list mailing list