[Python-Dev] Problem withthe API for str.rpartition()

Raymond Hettinger rhettinger at ewtllc.com
Sat Sep 2 01:47:21 CEST 2006


Currently, both the partition() and rpartition() methods return a (head, 
sep, tail) tuple and the only difference between the two is whether the 
partition element search starts from the beginning or end of the 
string.  When no separator is found, both methods return the string S 
and two empty strings so that 'a'.partition('x') == 'a'.rpartition('x') 
== ('a', '', ''). 

For rpartition() the notion of head and tail are backwards -- you 
repeatedly search the tail, not the head.  The distinction is vital 
because the use cases for rpartition() are a mirror image of those for 
partition().  Accordingly, rpartition()'s result should be interpreted 
as (tail, sep, head) and the partition-not-found endcase needs change so 
that 'a'.rpartition('x') == ('', '', 'a') .

The test invariant should be:
    For every s and p:    s.partition(p) == s[::-1].rpartition(p)[::-1]

The following code demonstrates why the current choice is problematic:

    line = 'a.b.c.d'
    while line:
        field, sep, line = line.partition('.')
        print field

    line = 'a.b.c.d'
    while line:
        line, sep, field = line.rpartition('.')
        print field

The second fragment never terminates.

Since this is a critical API flaw rather than a implementation bug, I 
think it should get fixed right away rather than waiting for Py2.5.1.



Raymond


More information about the Python-Dev mailing list