quiet conversion functions

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Apr 12 23:06:26 EDT 2006


"Tim Chase" <python.list at tim.thechases.com> wrote in message
news:mailman.4487.1144894602.27775.python-list at python.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





More information about the Python-list mailing list