iterate lines with regex

Carl Banks pavlovevidence at gmail.com
Mon Aug 3 17:04:12 EDT 2009


On Aug 3, 11:44 am, Robert Kern <robert.k... at gmail.com> wrote:
> On 2009-08-03 12:29, MRAB wrote:
>
>
>
>
>
> > Robert Kern wrote:
> > [snip]
>
> >> for line in readThis:
> >> key_match = key.search(line)
> >> if key_match is not None:
> >> this_key = key_match.group(1)
> >> # ... do something with this_key
> >> map_match = map.search(line)
> >> if map_match is not None:
> >> this_map = map_match.group(1)
> >> # ... do something with this_map
> >> parcel_match = parcel.search(line)
> >> if parcel_match is not None:
> >> this_parcel = parcel_match.group(1)
> >> # ... do something with this_parcel
>
> > re.search and re.match will return a MatchObject if successful or None
> > if unsuccessful. A MatchObject is always true, so you can simplify to:
>
> > ...
> > if key_match:
> > this_key = key_match.group(1)
> > # ... do something with this_key
> > ...
>
> True, but I prefer to maintain a consistent style for None-testing regardless of
> whether or not I am sure the not-None type will have a suitable __nonzero__
> implementation.


There's one thing to keep in mind.

In the unknown future, it's possible that re.match could be changed to
return an object with a false value that contains some information
about the reason for failure, or partial match information, or
something like that.

If that happens, code like:

   if m:

will continue to work, while code like

   if m is not None:

will suddenly fail.

Granted, it's not likely to happen for regexps but it could happen in
similar situations in other places.  I am one of the biggest critics
of implicit boolean values, but given that Python has it, I think it
is best to adhere strongly idiomatic uses like regexps.


Carl Banks



More information about the Python-list mailing list