15

What's the design thinking behind this?

To me it's easier to do something like

if string.index(substring) > -1:
    # do stuff

than trying to catch an exception. If the substring is not found, at least your program doesn't break.

Someone told me 'returning -1 is a bad pattern'. Why is that?

What is the Pythonic way for checking substring?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
melonccoli
  • 398
  • 1
  • 4
  • 14
  • 2
    Don't use `str` as a variable name. You can't use `str` type/function if you use `str` as a variable name. – falsetru Sep 18 '14 at 15:35
  • 1
    One can argue that a function should expect reasonable input, and raise an exception when this is violated. Unless you know to check for -1, you could accidentally use the return value incorrectly. – mdurant Sep 18 '14 at 15:39
  • Because [the documentation](https://docs.python.org/2/library/string.html#string.index) says so. Of course, you could use `find`, if you'd like – inspectorG4dget Sep 18 '14 at 15:41
  • 1
    Because -1 is a bad sentinel value for "not found"; negative indexing is allowed! (`find` gets away with it, I guess, because you still have `index` when you need the "strict" - aka "correct" - behavior) – roippi Sep 18 '14 at 15:44

3 Answers3

23

str.index() throws an exception; you were perhaps thinking of the str.find() method instead:

if string.find(substring) > -1:

The str.index() documentation explicitly states this:

Like find(), but raise ValueError when the substring is not found.

However, the correct way to test for substring membership is to use in:

if substring in string:
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

Because this way at least the return type of the function is fixed. Also your example is not pythonic, it should read:

if str in string:
    # do stuff
llogiq
  • 13,815
  • 8
  • 40
  • 72
1

Python operates under the principle of "easier to ask for forgiveness than permission" (EAFP), as explained in an answer by Sven Marnach. It allows the code for the common path to be kept together, making the logic easier to understand without inline error handling cluttering the flow. And in a program that uses import threading for non-blocking I/O, reading the variable only once makes time-of-check-to-time-of-use (TOCTTOU) bugs less likely than in look-before-you-leap style that some other languages encourage.

The major drawback of EAFP is that Python's syntax for exception handling doesn't mesh well with functional programming style. You can't catch exceptions for individual elements in the iterable input to a generator expression without defining and naming a function.

Community
  • 1
  • 1
Damian Yerrick
  • 4,602
  • 2
  • 26
  • 64