quiet conversion functions

T

Tim Chase

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
 
P

Paul McGuire

Tim Chase said:
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

Here are two approaches, one defines a function, the other a class.

-- Paul


"""
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?

"""

# define CBool as a method
def CBool(arg):
trueStrings = set( "Yes yes YES Y True true TRUE T Oui oui OUI Si si
SI".split() )
falseStrings = set( "No no NO N False false FALSE F Nyet nyet
NYET".split() )
if isinstance(arg,basestring):
if arg in trueStrings:
return True
elif arg in falseStrings:
return False
else:
raise ValueError, "could not determine boolean-ness of %s" % arg
else:
return bool(arg)

# or define CBool as a class
class CBool(object):
trueStrings = set( "Yes yes YES Y True true TRUE T Oui oui OUI Si si
SI".split() )
falseStrings = set( "No no NO N False false FALSE F Nyet nyet
NYET".split() )
def __init__(self,arg):
self.initarg = arg
if isinstance(arg,basestring):
if arg in self.trueStrings:
self.boolVal = True
elif arg in self.falseStrings:
self.boolVal = False
else:
raise ValueError, "could not determine boolean-ness of %s" %
arg
else:
self.boolVal = bool(arg)

def __nonzero__(self):
return self.boolVal

def __str__(self):
return "CBool(%s):%s" % (str(self.initarg),bool(self))

def testCBool(s):
print s,'->',CBool(s)

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


The class version prints out the following (the function gives similar
output):

Yes -> CBool(Yes):True
No -> CBool(No):False
True -> CBool(True):True
False -> CBool(False):False
Y -> CBool(Y):True
N -> CBool(N):False
T -> CBool(T):True
F -> CBool(F):False
None -> CBool(None):False
1 -> CBool(1):True
-1 -> CBool(-1):True
6.02e+023 -> CBool(6.02e+023):True
0 -> CBool(0):False
0.0 -> CBool(0.0):False
oui -> CBool(oui):True
si -> CBool(si):True
Nyet -> CBool(Nyet):False
Purple ->
Traceback (most recent call last):
File "CBool.py", line 75, in ?
testCBool("Purple") # returns True
File "CBool.py", line 56, in testCBool
print s,'->',CBool(s)
File "CBool.py", line 45, in __init__
raise ValueError, "could not determine boolean-ness of %s" % arg
ValueError: could not determine boolean-ness of Purple
 
C

Carl Banks

Tim said:
Is there some set of preexisting functions that do this sort
of "sensible" conversions without griping about crazy values
passed to them?

No, because this isn't Perl.

Seriously, it's a core principle of the Python language not to presume
what a user considers to be "sensible", because, frankly, what's
sensible isn't going to be the same for everyone. If you type "input
this" at a Python prompt, you'll see a list of guidelines the language
designers use. The one in effect here is: In the face of ambiguity,
refuse the temptation to guess.

Out of curiosity, what would Perl do?

$ perl -e 'print int("3.14")'; echo
3
$ perl -e 'print int("33fwegfgqer")'; echo
33
$ perl -e 'print int("3OO3")'; echo
3
$ perl -e 'print int({"a","b","c","d"})'; echo
135601192
$ perl -e 'print int("hello, world")'; echo
0

Somebody (I'm guessing Larry Wall himself) thought it was "sensible"
for int() to return the internal pointer of the hash.


Carl Banks
 
S

Sion Arrowsmith

Tim Chase said:
def CFloat(value):
try:
value = float(value)
except (ValueError, TypeError):
value = 0
return value
<type 'int'>

I think you want value = 0.0 . And you might also want to consider
what errors you may be masking in silently turning *anything* into
a valid number.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,292
Messages
2,571,494
Members
48,183
Latest member
GarfieldBa

Latest Threads

Top