Another Wart! string.find() [ was: namespace issue? ]

Donn Cave donn at u.washington.edu
Fri Jun 22 12:03:04 EDT 2001


Quoth Michael Powe <michael+gnus at trollope.org>:
| >>>>> "Andrew" == Andrew Dalke <dalke at acm.org> writes:
|     Andrew> Steven D. Majewski wrote:
|     >> It probably *ought* to return None for not found:
|     >> "string"[None] yields an exception: "TypeError: sequence index
|     >> must be integer" while "string"[-1] returns "g" so a coding
|     >> error is likely to slip thru without an exception.
|
|     >> I'ld love to see it fixed, however, I suspect that in this
|     >> case, many lines of installed code trumps Computer Programming
|     >> for Everybody!
|
|     >>>> print string.find.__doc__
|     Andrew> find(s, sub [,start [,end]]) -> in
|
|     Andrew> Return the lowest index in s where substring sub is found,
|     Andrew> such that sub is contained within s[start,end].  Optional
|     Andrew> arguments start and end are interpreted as in slice
|     Andrew> notation.
|
|     Andrew> Return -1 on failure.
|     >>>> print string.index.__doc__
|     Andrew> index(s, sub [,start [,end]]) -> int
|
|     Andrew>  Return the lowest index in s where substring sub is
|     Andrew> found, such that sub is contained within s[start,end].
|     Andrew> Optional arguments start and end are interpreted as in
|     Andrew> slice notation.
|
|     Andrew>  Raise ValueError if not found.
|
| Pardon the dumb question, but can you test this in a conditional, as
| in 
|
| if not string.index(s,sub) : /* and so forth and so on */

Nope.  If sub occurs at the beginning of s, then the result will
still be 0.  That's false, but I assume the sense of your program
would want it to be true.

So I find no wart.  A function that returns string indices must
be expected to return 0 as a valid result.  Its return cannot be
treated as a boolean.  The only way out is to a) ban functions
that return string indices, or b) start indices at 1.  The latter
would make some sense, but 0 works for me, even if after all these
years it sometimes bites too.  The former is kind of silly, but
you could imagine a slice return that would be false on failure.

Given that you can't treat find or index as a boolean, there is
no fault I can see with its -1 failure return.  In fact it would
be worse if it were false.  Usage that doesn't work reliably
ideally shouldn't work at all, or it's all the harder to diagnose.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list