samb a écrit :
Hi,

I've found a work around, inspired from Rob Williscroft :

class ReMatch(object):
    """
        Object to be called :
        1st time : do a regexp.match and return the answer (args:
regexp, line)
        2nd time : return the previous result (args: prev)
    """
    def __call__(self, regexp='', line='', prev=False):
        if prev:
            return self.prev_match
        self.prev_match = re.match(regexp, line)
        return self.prev_match

re_match = ReMatch()

if re_match(r'define\s+(\S+)\s*{$', line):
    m = re_match(prev=True)
    # do some logic with m
elif re_match(r'include\s+(\S+)$', line):
    m = re_match(prev=True)
    # do some logic with m
else
    # do some logic

Hope this is efficient ... I guess yes.

A direct attribute access is cheaper than a method call, and makes for a simpler API too:

class ReMatch(object):
     match = None

     def __call__(self, regexp, source):
         self.match = re.match(regexp, source)
         return self.match


re_match = ReMatch()

if re_match(r'define\s+(\S+)\s*{$', line):
     m = re_match.match
     # do some logic with m
elif re_match(r'include\s+(\S+)$', line):
      m = re_match.match
     # do some logic with m

My 2 cents...
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to