Exceptions provide very handy ways of performing simple tests. For example, if you want to know if the contents of a string represent an integer, why not just try to convert it? That's what IsInt() does.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
def IsInt( str ): """ Is the given string an integer? """ ok = 1 try: num = int(str) except ValueError: ok = 0 return ok def IsAllDigits( str ): """ Is the given string composed entirely of digits? """ import string match = string.digits ok = 1 for letter in str: if letter not in match: ok = 0 break return ok if __name__ == '__main__': print IsInt('23') print IsInt('sd') print IsInt('233835859285') print IsAllDigits('233835859285')
Similar tests can be written for types other than Integer. Exceptions provide a direct way of performing tests that could otherwise be quite laborious.
It should be noted that this "type" test is semantically quite different from testing whether a string contains digits. IsAllDigits() will help you there.
isdigit method of string objects. s.isdigit() [in Python 2.0 and later] is a faster version of this isAllDigits function, except that ''.isdigit() is 0 [only if s has at least one digit, AND nothing but digits, does isdigit succeed] so if you want an empty string to be OK you need to code
This doesn't diminish the value of the exception-based approach to testing general properties, of course!
thanks. Thanks for the comment. This specific function was written before Python 2.0. As noted, the general method is still useful, and is often missed by those new to exceptions.
A minor speed/memory tweak. A very minor consideration, but to increase speed and minimize memory usage, I return at the point of determination. Any problems with this I do not see?
This is the sin of "expection handling". I recently wrote exactly the same code in a job interview. Two days later I saw this page on Wikipedia and I was pretty embarrassed:
It's an ironic pun meaning you're using something that's supposed to be for exceptions, only for something you _expect_. The main reason it's bad (especially if you do this in more complicated situations) is that some other exception may occur, and your except clause would catch it and prevent it from propagating. A minor reason is that exception handling isn't designed to be fast.
I'm a little miffed that Python doesn't have an "IsInt"-like function, but str.isdigit() is close enough for my use (thanks for the clue!).
Don't worry about someone's neurotic idea of stylistic "sins"... worry about the "sin" of failure. I'd hire you for that perfectly good code (and pass someone over for bowing down to an uncited opinion piece in wikipedia). Sure exceptions can be abused (e.g. applying them too sloppily and broadly, like the situation you mention), but it doesn't matter one bit that they're called "exceptions"... any more than you can't "go" at a "stop light" because it only has "stop" in its name. The implementation (i.e. whether it's designed to be fast) and the reasonable use cases of exceptions will vary from language to language. Anyone who says you shouldn't or can't use this approach should put their efforts into demonstrating a better solution.
Given a string of user input, how do I know I can call int(string) safely (in my flight control system :) when a user sometimes types '-1' and sometimes mistypes just '-' ? try: int() will succeed for any and all valid inputs, and fail for any and all invalid input. why settle for incomplete coverage or cases you forgot to consider & test for, when the built in interpreter will do a Perfect match for you?