I have a function that expects real numbers (either integers or floats) as its input, and I’m trying to validate this input before doing mathematical operations on it.
My first instinct is to cast inputs as floats from within a try-except block.
try: myinput = float(input) except: raise ValueError('input is not a well-formed number')
I could also call isinstance(mydata, (float, int, long) ) but the list of ‘all these could be numbers’ seems a bit inelegant to me.
What’s the most pythonic way of going about it? Is there another option I overlooked?
To quote myself from How much input validation should I be doing on my python functions/methods?:
Thus, the best option is to leave the type checking up to Python. If the calculation fails, Python’s type checking will give an exception, so if you do it yourself, you just duplicate code which means more work on your behalf.