Don't want to do the regexp test twice
Bengt Richter
bokr at oz.net
Fri Jul 25 11:03:07 EDT 2003
On 25 Jul 2003 02:17:24 GMT, bokr at oz.net (Bengt Richter) wrote:
[...]
>You can spell
>
> ... elif setattr(obj,'mat', pat.search(line)) or obj.mat:
> ... print repr(obj.mat), obj.mat.groups(), obj.mat.group()
>
>a little slicker if you make a special object to hold a binding to
>the pat.search result, e.g., h is the Holder instance in the following,
>which remembers the last thing passed to it and immediately returns it,
>and also returns that last thing on being called without an arg:
>
> >>> mylist
> ['', 'a', 'bc', 'def', 'ghij']
> >>> h = Holder()
> >>> for line in mylist:
> ... if 1==2: 'naw'
> ... elif 3==4: 'neither'
> ... elif h(pat.search(line)):
> ... print repr(h()), h().groups(), h().group()
> ... elif 4==5: 'haw'
> ... else:
> ... print 'final else'
> ...
> final else
> final else
> final else
> <_sre.SRE_Match object at 0x007F6FC0> () def
> <_sre.SRE_Match object at 0x007F6F80> () ghi
>
>Obviously
> ... print repr(h()), h().groups(), h().group()
>could have been
> ... mat=h(); print repr(mat), mat.groups(), mat.group()
>instead.
>
Sorry, I seem to have snipped out a Holder definition, in case anyone cares:
>>> class Holder(object):
... def __call__(self, *args):
... if args: self.val = args[0]
... return self.val
...
>>> h = Holder()
>>> h(123)
123
>>> h()
123
>>> h(345),h(),h(678),h() # result depends on left-to-right eval here
(345, 345, 678, 678)
Regards,
Bengt Richter
More information about the Python-list
mailing list