quiet conversion functions

Tim Chase python.list at tim.thechases.com
Wed Apr 12 22:16:15 EDT 2006


Are there existing "quiet" conversion functions?  Kin of 
int() and float()?

My aim would be to call a function that would guarntee that 
the result was of the defined type, choosing sensible 
defaults if needed.  Example problems include:

int("3.14")
int(None)
int(__builtins__)
int("hello")

For the 2nd through 4th examples, I'd consider zero to be a 
reasonable response from this phantasmic function.  For the 
first one, it would be sensible to return "3".  Wrapping it 
in a float() call:

	int(float("3.14"))

seems a little smarter, but is still more overhead than a 
mythical justGiveMeAStinkingInt() call.

At the moment, I've churned my own helper functions, of the form

def CInt(value):
	try:
		value = int(value)
	except (ValueError, TypeError):
		try:
			value = int(float(value))
		except (ValueError, TypeError):
			value = 0
	return value

def CFloat(value):
	try:
		value = float(value)
	except (ValueError, TypeError):
		value = 0
	return value


Is there some set of preexisting functions that do this sort 
of "sensible" conversions without griping about crazy values 
passed to them?  If not, are there other exceptions that 
might be thrown that I haven't considered yet?

It would also be handy to have a CBool that is a little 
smarter about strings (though I18N'ing it becomes a little 
trickier...)

CBool("Yes") # returns True
CBool("No") # returns False
CBool("True") # returns True
CBool("False") # returns False
CBool("Y") # returns True
CBool("N") # returns False
CBool("T") # returns True
CBool("F") # returns False
CBool(None) # returns False
CBool(1) # returns True for any non-zero
CBool(0) # returns False
CBool("oui") # returns True?
CBool("si") # returns True?
CBool("Nyet") # returns False?

Any tips in this direction as well?

My first shot is something like the rather ugly

	def CBool(value):
		if value:
			# There's prob. a better way
			# to check if it's a string...
			if type(value) is type(""):
				return (value[0].lower() in
					"ytos")
			else:
				return True
		else:
			return False

Thanks for any tips or hints towards deuglification,

-tkc









More information about the Python-list mailing list