Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 25 lines
def IsInt( str ):
	""" Is the given string an integer?	"""
	ok = 1
		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
	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.


Alex Martelli 20 years, 1 month ago  # | flag

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

s.isdigit() or not s

This doesn't diminish the value of the exception-based approach to testing general properties, of course!

Robin Parmar (author) 20 years, 1 month ago  # | flag

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.

FMHj . 19 years, 5 months ago  # | flag

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?

def IsInt( str ):
   """ Is the given string an integer?"""
      num = int(str)
      return 1
   except ValueError:
      return 0
Steve Witham 13 years, 5 months ago  # | flag

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!).

karkfum 12 years, 1 month ago  # | flag

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?

Created by Robin Parmar on Tue, 10 Apr 2001 (PSF)
Python recipes (4591)
Robin Parmar's recipes (9)

Required Modules

Other Information and Tasks