I don't get the question.
There are two things with wildly different semantics tossed around as "alternatives".
A type conversion is one thing. It works with any object that supports __float__
, which can be quite a variety of objects, few of which are actually numeric.
try:
myinput = float(input)
except:
raise ValueError("input is not a well-formed number")
# at this point, input may not be numeric at all
# it may, however, have produced a numeric value
A type test is another thing. This works only with objects that are proper instances of a specific set of classes.
isinstance(input, (float, int, long) )
# at this point, input is one of a known list of numeric types
Here's the example class that responds to float
, but is still not numeric.
class MyStrangeThing( object ):
def __init__( self, aString ):
# Some fancy parsing
def __float__( self ):
# extract some numeric value from my thing
The question "real numbers (either integers or floats)" is generally irrelevant. Many things are "numeric" and can be used in a numeric operation but aren't ints or floats. For example, you may have downloaded or created a rational numbers package.
There's no point in overvalidating inputs, unless you have an algorithm that will not work with some types. These are rare, but some calculations require integers, specifically so they can do integer division and remainder operations. For those, you might want to assert that your values are ints.