[Python-Dev] Remove str.find in 3.0?

Tim Peters tim.peters at gmail.com
Sat Aug 27 18:38:47 CEST 2005


[Raymond Hettinger, rewrites some code]
> ...
> --- StringIO.py ---------------
> 
> i = self.buf.find('\n', self.pos)
> if i < 0:
>    newpos = self.len
> else:
>    newpos = i+1
> . . .
> 
> 
> try:
>    i = self.buf.find('\n', self.pos)
> except ValueError():
>    newpos = self.len
> else:
>    newpos = i+1
> . . .

You probably want "except ValueError:" in all these, not "except ValueError():".

Leaving that alone, the last example particularly shows one thing I
dislike about try/except here:  in a language with properties, how is
the code reader supposed to guess that it's specifically and only the
.find() call that _can_ raise ValueError in

    i = self.buf.find('\n', self.pos)

?  I agree it's clear enough here from context, but there's no
confusion possible on this point in the original spelling:  it's
immediately obvious that the result of find() is the only thing being
tested.  There's also strong temptation to slam everything into the
'try' block, and reduce nesting:

newpos = self.len
try:
    newpos = self.buf.find('\n', self.pos) + 1
except ValueError:
    pass

I've often seen code in the wild with, say, two-three dozen lines in a
``try`` block, with an "except AttributeError:" that was _intended_ to
catch an expected AttributeError only in the second of those lines. 
Of course that hides legitimate bugs too.  Like ``object.attr``, the
result of ``string.find()`` is normally used in further computation,
so the temptation is to slam the computation inside the ``try`` block
too.

.find() is a little delicate to use, but IME sloppy try/except
practice (putting much more in the ``try`` block than the specific
little operation where an exception is expected) is common, and harder
to get people to change because it requires thought instead of just
reading the manual to see that -1 means "not there" <0.5 wink>.

Another consideration is code that needs to use .find() a _lot_.  In
my programs of that sort, try/except is a lot more expensive than
letting -1 signal "not there".


More information about the Python-Dev mailing list