[Python-ideas] Deprecate str.find
Nick Coghlan
ncoghlan at gmail.com
Sun Jul 17 09:15:14 CEST 2011
On Sun, Jul 17, 2011 at 11:40 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> Raymond Hettinger wrote:
>> Now, the thread is venturing into the typical python-ideas
>> world of making-up random use cases and APIs. Something like str.find()
>> is in many languages and it is definitely not the
>> norm for them to have found a need to both be able to
>> return -1 or to supply a default value.
>
> Nick's proposal was to enhance str.index(), not string.find(); Having
> str.index() accept a value to return on failure instead of raising an
> exception means it could do both jobs, and would also make it much less
> likely to wrongly use the failure return value of -1 from str.find() which
> is, unfortunately, a legitimate index value.
Indeed, the problem as I see it is that our general idiom for
functions and methods that raise 'Not Found' exceptions is to accept
an optional parameter that specifies a value to return in the Not
Found case.
For historical reasons, we currently break that idiom for index()
methods: instead of supplying an extra parameter to str.index, one
instead switches to a completely different method (.find()) with no
control over the sentinel value returned (it's always -1). For other
sequences (e.g. list), there's no find equivalent, so you *have* to
write the exception handling out explicitly.
My proposal is to update the signature of index() (for all sequences,
including the ABC) to follow the standard 'Not Found' idiom by
accepting a 'missing' parameter that is returned for those cases where
ValueError would otherwise be raised.
Code that uses str.find would continue to work, but the recommended
alternative would be obj.index(x, missing=None) (or appropriate
default value). I would advise against any actual deprecation of
str,find (cf. the deliberate lack of optparse deprecation).
It's unfortunate that backwards compatibility means we can't use the
more descriptive name, but that's life.
However, I already have too much on my plate to push this forward for
Python 3.3. I'm able to offer advice if someone would like to try
their hand at writing a PEP, though.
Regards,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list