2

Coming from a Java background I'm currently learning Python and I found this example in a Python beginner book. It's proposing the use of the ValueError exception in a function for a spreadsheet-like calculation to return 0 for empty cells like this:

def cell_value(string):
  try:
    return float(string)
  except ValueError:
    if string == "":
      return 0
    else:
      return None

Now, to my understanding, in the Java world, such a use of exceptions would be frowned upon, because having an empty cell in a spreadsheet and interpreting it as 0 is clearly not an exceptional condition but rather normal program flow and in Java "exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow." (Joshua Bloch: Effective Java)

I already read another similar question and answer suggesting that this rule might not be adhered to as strictly in the Python world, but I'm still not sure about the given example.

Would the use of ValueError as illustrated in the function above be considered bad practice in Python or not?

anothernode
  • 5,100
  • 13
  • 43
  • 62
  • whether it is a bad practice or not depends on the context imho. What are you doing with all these cell values? For example, if you were adding them together, this approach would be "ok". – Ma0 Jan 26 '18 at 10:10
  • 1
    Probably moving the `if string == ""` before the cast to `float` would make more sense, but you'll still need the try-catch block around the cast, with the difference that then the `except` branch only returns `None` – GPhilo Jan 26 '18 at 10:11
  • Agree with @GPhilo, also `if not string:` will suffice to test for an empty string; in Python EAFP is encouraged over LBYL https://docs.python.org/3/glossary.html#term-eafp – Chris_Rands Jan 26 '18 at 10:16
  • Yeah, I guess there's no good reason to put the empty string test into the except block instead of the try block. And if it's in the try block, the except block is left with handling only truly exceptional conditions. Makes sense, thanks! – anothernode Jan 26 '18 at 10:21
  • @anothernode I think the empty string test should be outside the try-except clause altogether, i.e. before the try, you're not expecting the empty string test to raise a ValueError – Chris_Rands Jan 26 '18 at 10:24
  • @Chris_Rands: Makes even more sense! :) – anothernode Jan 26 '18 at 10:26

0 Answers0