470,811 Members | 1,051 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,811 developers. It's quick & easy.

quiet conversion functions

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


Apr 13 '06 #1
3 1260
"Tim Chase" <py*********@tim.thechases.com> wrote in message
news:ma***************************************@pyt hon.org...
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
Apr 13 '06 #2
Tim Chase wrote:
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

Apr 13 '06 #3
Tim Chase <py*********@tim.thechases.com> wrote:
def CFloat(value):
try:
value = float(value)
except (ValueError, TypeError):
value = 0
return value

type(CFloat(None))

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

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Apr 13 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

14 posts views Thread by Dave | last post: by
6 posts views Thread by Lionel B | last post: by
16 posts views Thread by frs | last post: by
4 posts views Thread by Påhl Melin | last post: by
1 post views Thread by hunter hou | last post: by
19 posts views Thread by xdevel | last post: by
8 posts views Thread by Smithers | last post: by
2 posts views Thread by xtrigger303 | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.