[Python-Dev] basenumber redux

M.-A. Lemburg mal at egenix.com
Tue Jan 17 11:02:22 CET 2006


Alex, I think you're missing a point here: what you are looking
for is an interface, not a base class - simply because the
assumptions you make when finding a "KnownNumberTypes" instance
are only related to an interface you expect them to provide.

A common case class won't really help all that much with this,
since the implementations of the different types will vary a
lot (unlike, for example, strings and Unicode, which implement
a very common interface) and not necessarily provide a common
interface.

If you look at the Python C API, you'll find that "a number"
is actually never tested. The tests always ask for either
integers or floats.

The addition of a basenumber base class won't make these any
simpler.

Here's a snippet which probably does what you're looking for
using Python's natural way of hooking up to an implicit
interface:

import UserString

STRING_TYPES = (basestring, UserString.UserString)

def floatnumber(obj):
    if isinstance(obj, STRING_TYPES):
        raise TypeError('strings are not numbers')

    # Convert to a float
    try:
        return float(obj)
    except (AttributeError, TypeError, ValueError):
        raise TypeError('%r is not a float' % obj)

def intnumber(obj):
    if isinstance(obj, STRING_TYPES):
        raise TypeError('strings are not numbers')

    # Convert to an integer
    try:
        value = int(obj)
    except (AttributeError, TypeError, ValueError):
        raise TypeError('%r is not an integer' % obj)

    # Double check so that we don't lose precision
    try:
        floatvalue = floatnumber(obj)
    except TypeError:
        return value
    if floatvalue != value:
        raise TypeError('%r is not an integer' % obj)

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jan 17 2006)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::


More information about the Python-Dev mailing list