affectation in if statement

Peter Otten __peter__ at web.de
Tue Mar 16 06:45:40 EDT 2010


samb wrote:

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

No; just accessing the prev_match attribute instead of passing a flag to the 
__call__() method is more efficient and easier to read. I think the latter 
is the relevant point...

Peter



More information about the Python-list mailing list