[Python-ideas] Deprecate str.find

Masklinn masklinn at masklinn.net
Fri Jul 15 19:18:58 CEST 2011


On 2011-07-15, at 19:06 , Bruce Leban wrote:

> 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
> 
Note that you could replace `do_more` by a use of `i`:

i = None
try:
    i = s.index(sub)
except ValueError:
    result = 'not found'

if i is not None:
    do 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

There's always the `in` alternative:

if sub not in s:
    result = 'not found'
else:
    do stuff with s and s.index(sub)

it's a more fluent interface, and uses less error-prone APIs, though it does search twice through `s`.

(an other option would be to build this feature via higher-order functions, but that's not really one of Python's forte)


More information about the Python-ideas mailing list