How can we write a test that checks if a value is numeric, and throw an exception is the value is not numeric? Do we need regular expressions in this case?
Thanks.
You can use the numbers module.
>>> import numbers
>>> isinstance(1, numbers.Number)
True
>>> isinstance('a', numbers.Number)
False
It should be noted that complex numbers are considered part of numbers.Number as well, if you only want real numbers you can do:
>>> import numbers
>>> isinstance(1, numbers.Real)
True
>>> isinstance(1j, numbers.Real)
False
As far as throwing an exception if a value is not numeric I would just do:
assert isinstance(my_value, numbers.Real)
Which will throw AssertionError if my_value is not a real number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With