[Python-ideas] Deprecate str.find

Nick Coghlan ncoghlan at gmail.com
Sat Jul 16 11:46:59 CEST 2011


On Sat, Jul 16, 2011 at 7:11 PM, M.-A. Lemburg <mal at egenix.com> wrote:
> Georg Brandl wrote:
>> By the way: str.index() raises ValueError, not IndexError, if the substring
>> isn't found.  That's one argument against "the index() API is foolproof,
>> while the find() API isn't".
>
> That's because the *value* passed as argument to .index() isn't
> found. Which error class to use often depends on your view point,
> so in some cases it may seem natural to you, in others you have
> a different POV, and it feels wrong :-)

Yeah, but trying to catch IndexError instead of ValueError is a pretty
easy (and understandable) mistake to make, given the correspondence in
names and logical train of thought "index() tells me the index where a
substring can be found, IndexError is used to denote that a given
index doesn't exist, so if the requested index doesn't exist, then
this function will throw IndexError". Easily detected by testing, but
still unintuitive and annoying.

If IndexError had instead been called IndexNotFound, then there would
never have been the slightest question as to which exception should
have been thrown.

Too late to change it now, though. We just all have to learn that,
from the str.index point of view, failing to find a substring means
there's something *wrong* with one (or both) of the passed in strings
rather than the less opinionated "the index you have requested doesn't
actually exist".

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list