My code is processing data files that contains integer values as strings terminating with a .0. For example, 1234
is "1234.0"
. These strings should be converted to integers, which is simple enough by first converting to a float and then an int:
foo = "1234.0"
foo = int(float(foo))
There is a possibility that the string could be "nan"
however, in which case this code will throw an error when converting to int:
ValueError: cannot convert float NaN to integer
These values should be changed to None. I see two approaches to handling this:
foo = "nan"
try:
foo = int(float(foo))
except ValueError as e:
if 'cannot convert float NaN to integer' in str(e):
foo = None
else:
raise
or
import math
foo = "nan"
foo = float(foo)
if math.isnan(foo):
foo = None
else:
foo = int(foo)
As exceptions as flow control is considered a good practice in Python I would usually favour something like the first option. However, this approach of explicitly checking the message of the exception as using that as flow control (i.e, if this message then do this otherwise raise) feels intuitively 'dirty'.
Is checking for specific error messages as a form of flow control generally considered a good or bad practice in Python and why?