quiet conversion functions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tim Chase

    #1

    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 justGiveMeAStin kingInt() 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






  • Paul McGuire

    #2
    Re: quiet conversion functions

    "Tim Chase" <python.list@ti m.thechases.com > wrote in message
    news:mailman.44 87.1144894602.2 7775.python-list@python.org ...[color=blue]
    > 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 justGiveMeAStin kingInt() 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
    >[/color]

    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,a rg):
    self.initarg = arg
    if isinstance(arg, basestring):
    if arg in self.trueString s:
    self.boolVal = True
    elif arg in self.falseStrin gs:
    self.boolVal = False
    else:
    raise ValueError, "could not determine boolean-ness of %s" %
    arg
    else:
    self.boolVal = bool(arg)

    def __nonzero__(sel f):
    return self.boolVal

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

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

    testCBool("Yes" ) # returns True
    testCBool("No") # returns False
    testCBool("True ") # returns True
    testCBool("Fals e") # 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.02E 23) # 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("Purp le") # 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):Tru e
    False -> CBool(False):Fa lse
    Y -> CBool(Y):True
    N -> CBool(N):False
    T -> CBool(T):True
    F -> CBool(F):False
    None -> CBool(None):Fal se
    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):Fals e
    oui -> CBool(oui):True
    si -> CBool(si):True
    Nyet -> CBool(Nyet):Fal se
    Purple ->
    Traceback (most recent call last):
    File "CBool.py", line 75, in ?
    testCBool("Purp le") # 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


    Comment

    • Carl Banks

      #3
      Re: quiet conversion functions

      Tim Chase wrote:[color=blue]
      > Is there some set of preexisting functions that do this sort
      > of "sensible" conversions without griping about crazy values
      > passed to them?[/color]

      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("33fwegfgqe r")'; 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

      Comment

      • Sion Arrowsmith

        #4
        Re: quiet conversion functions

        Tim Chase <python.list@ti m.thechases.com > wrote:[color=blue]
        >def CFloat(value):
        > try:
        > value = float(value)
        > except (ValueError, TypeError):
        > value = 0
        > return value[/color]
        [color=blue][color=green][color=darkred]
        >>> type(CFloat(Non e))[/color][/color][/color]
        <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 -- siona@chiark.gr eenend.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

        Comment

        Working...