[Python-ideas] Deprecate str.find

Bruce Leban bruce at leapyear.org
Fri Jul 15 19:06:27 CEST 2011


It seems to me that the solution is that you should never use find and use
index instead. You could even modify pylint/etc. to flag any use of find as
an error.

That doesn't mean it should be deprecated so everyone else has to follow
you. Deprecated now => removed in the future. While many can agree that
warnings in the documentation about common mistakes in using APIs is a good
thing, that doesn't translate into consensus that we should remove the API
that might be misused. The documentation already says "The find() method
should be used only if you need to know the position of sub. To check if sub
is a substring or not, use the in operator."

There is *no* general solution to the problem of people misusing APIs. Even
with index someone can still write

if s.index(sub):

which probably doesn't do what they were thinking. Should we remove that
too?

Note that one reason people might prefer find over index is that exceptions
constrain how you write the code:

try:
    i = s.index(sub)
    do lots of stuff with s and i
except ValueError:
    result = 'not found'


In this case the try wraps way too much code so it could catch a ValueError
in the middle of 'stuff'. Here's correct code:

try:
    i = s.index(sub)
    do_more = True
except:
    result = 'not found'
    do_more = False
if do_more:
    do lots of stuff with s and i


Do you think that's better than:

i = s.find(sub)
if i < 0:
    result = 'not found'
else:
    do lots of stuff with s and i


--- Bruce
Follow me: http://www.twitter.com/Vroo http://www.vroospeak.com




On Fri, Jul 15, 2011 at 9:51 AM, Mike Graham <mikegraham at gmail.com> wrote:

> On Fri, Jul 15, 2011 at 12:31 PM, Antoine Pitrou <solipsis at pitrou.net>
> wrote:
> > While this would be a very good argument to make if we were currently
> > designing the str API, I don't think the benefits of suppressing
> > str.find outweight the burden of converting old code to use a different
> > idiom.
> >
> > We could choose to write something about it in the documentation,
> > though.
> >
> > Regards
> >
> > Antoine.
>
>
> That could be just as suitable. To be honest, I can't really see too
> much of a difference between a stronger note about the problems I
> perceive with str.find in the documentation and a note that uses the
> word "deprecated". There certainly wouldn't be occasion in the
> foreseeable future for you actually to remove str.find.
>
> Mike
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110715/7897746b/attachment.html>


More information about the Python-ideas mailing list