reducing if statements and error handling

Rich Harkins rharkins at thinkronize.com
Tue Aug 21 10:00:35 EDT 2001


One way to validate this is using the following pattern:

def f(n):
	n=int(n)				# Will throw ValueError if not convertable.
	...

This would then accept integers, and anything that can be converted to an
int.  This should be used somewhat judiciously, however, as it will accept a
lot of different types of input.  If what you want is to make sure that n is
definitely an int then the following will do the trick:

def f(n):
	assert type(n) is type(0)
	...

Which will raise an AssertionError if n is not an integer.  If you prefer a
negative return value then:

def f(n):
	if type(n) is not type(0): return -1
	...
	# Returns 0/None if success...

Of these I personally generally prefer the second (assert type(n) is
type(0)) since it doesn't require the caller to understand "magic" return
values and ensures a solid interface between the caller and the called.

Just some thoughts...
Rich

[original message deleted to conserve bits]





More information about the Python-list mailing list