[Numpy-discussion] help! type 'float64scalar' is not type 'float'
Christopher Barker
Chris.Barker at noaa.gov
Thu Aug 3 13:33:54 EDT 2006
Sebastian Haase wrote:
> Finally I traced the problem down to a utility function:
> "is_number" - it is simply implemented as
> def is_number(val):
> return (type(val) in [type(0.0),type(0)])
> OK - how should this have been done right ?
Well, as others have said, python is uses "duck typing", so you really
shouldn't be checking for specific types anyway -- if whatever is passed
in acts like it should, that's all you need not know. However, sometimes
it does make sense to catch the error sooner, rather than later, so that
it can be obvious, or handled properly, or give a better error message,
or whatever.
In this case, I still use a "duck typing" approach: I don't need to know
exactly what type it is, I just need to know that I can use it in the
way I want, and an easy way to do that is to turn it into a known type:
def is_number(val):
try:
float(val)
return True
except ValueError:
return False
Though more often, I'd just call float on it, and pass that along,
rather than explicitly checking
This works at least with numpy float64scalar and float32scalar, and it
should work with all numpy scalar types, except perhaps the long types
that don't fit into a Python float.
it'll also turn string into floats if it can, which may or may not be
what you want.
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
NOAA/OR&R/HAZMAT (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the NumPy-Discussion
mailing list