question of style

Paul Rubin http
Sun Jul 5 15:12:25 CEST 2009


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> > I wouldn't say Python's None is terrible,...
> No, wait, I tell I lie... re.search() sometimes bites me, because 
> sometimes it returns None and sometimes it returns a matchobject and I 
> don't use re often enough to have good habits with it yet.

re is a common source of this type of bug but there are others.
> There are three natural approaches to (say) re.search() for dealing with 
> failure:
> 
> (1) return a sentinel value like None;
> (2) return a matchobject which tests False;
> (3) raise an exception.

4. Have re.search return a bool and possible matchobject separately:

   put_match_here = []
   if re.search(pat, s, target=put_match_here):
      do_something_with(put_match_here[0])

or alternatively (cleaner), have a new type of object which supports
search operations while self-updating with the match object:

   mt = re.match_target()
   ...
   if mt.search(pat, s):
      do_something_with(mt.match)
   if mt.search(pat2, s):
      do_another_thing_with(mt.match)
   ...

This is sort of inspired by what Perl does.  I often do something like
this because it makes it cleaner to chain a series of matches.



More information about the Python-list mailing list