[Python-Dev] Proof of the pudding: str.partition()

Nick Coghlan ncoghlan at gmail.com
Mon Aug 29 13:16:18 CEST 2005


Raymond Hettinger wrote:
> Most patterns using str.find() directly translated into an equivalent
> using partition.  The only awkwardness that arose was in cases where the
> original code had a test like, "if s.find(pat) > 0".  That case
> translated to a double-term test, "if found and head".

That said, the latter would give me much greater confidence that the test for 
"found, but not right at the start" was deliberate. With the original version 
I would need to study the surrounding code to satisfy myself that it wasn't a 
simple typo that resulted in '>' being written where '>=' was intended.

> With further ado, here are the comparative code fragments:

There's another one below that you previously tried rewriting to use str.index 
that also benefits from str.partition. This rewrite makes it easier to avoid 
the bug that afflicts the current code, and would make that bug raise an 
exception if it wasn't fixed - "head[-1]" would raise IndexError if the head 
was empty.

Cheers,
Nick.

--- From ConfigParser.py (current) ---------------

optname, vi, optval = mo.group('option', 'vi', 'value')
if vi in ('=', ':') and ';' in optval:
     # ';' is a comment delimiter only if it follows
     # a spacing character
     pos = optval.find(';')
     if pos != -1 and optval[pos-1].isspace():
         optval = optval[:pos]
optval = optval.strip()

--- From ConfigParser.py (with str.partition) ---------------

optname, vi, optval = mo.group('option', 'vi', 'value')
if vi in ('=', ':'):
     # ';' is a comment delimiter only if it follows
     # a spacing character
     head, found, _ = optval.partition(';')
     if found and head and head[-1].isspace():
         optval = head
optval = optval.strip()


-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list