I have a function that expects to operate on a numeric type. I am reading the numbers to operate on from a file, so when I read them they are strings, not numeric. Is it better to make my function tolerant of other types (option (A) below), or convert to a numeric before calling the function (option (B) below)?
# Option (A)
def numeric_operation(arg):
i = int(arg)
# do something numeric with i
# Option (B)
def numeric_operation(arg):
# expect caller to call numeric_operation(int(arg))
# do something numeric with arg
If your function expects to operate on numeric data, then you are probably best off allowing Python to throw a
TypeErrorif it doesn’t receive one and something goes wrong. I would say, do the conversion outside and handle the exception.