Thursday, October 03, 2024

Python serious number handling annoyances

It is very strange and weird that Python is not capable out of the box to properly determine if an arbitrary value (a variable) is numeric, an integer, or a float!!! 

Perhaps, there are other widely used and recognized packages (I strongly suspect e.g. NumPy) available to do that for you, but I think such fundamental functions should be part of the core of Python.

str(value).isnumeric() does not work properly when the value is a float. It returns false. It appears to work reliably only if the len(str(value)) = 1. What a joke!  This is absolutely insane and unexpected!!!

isinstance(value, int) or isinstance(value, float) are similarly unreliable depending on whether the value is a string or not. I also tried int(str(value)) and float(str(value)).

isinstance(value, float) returns true when the value is clearly and typed (using the int() function) as an integer. This is absolutely insane and unexpected!!!!

isinstance(v, numbers.Number) also fails when the value is a str(value) even if the value is an integer, i.e. int(value) or a float, i.e. float(value). This is absolutely insane and unexpected!!!!

math.isnan(v) does not work with str(value) either! This is absolutely insane and unexpected!!!!

int(value) converts a float or a str(float) into an integer when the float decimals are less than .01. This is absolutely insane and unexpected!!!!

I found that str(value).isalpha() appears to work most reliably to determine that the value is a number and it does not crash!

Unlike str(value).isalnum() fails if the value is an clearly an single digit integer and nothing but an integer! It returns False if the value is a float, which is expected. The flaw here is that one character is enough for this function according to the documentation, while you would expect a minimum length requirement of two characters. This is absolutely insane and unexpected!!!!

In the end, I had to write my own functions to handle this ambiguity!

P.S. I probably wasted at least several hours to understand this issue and develop more reliable functions on my own! What a waste!

Caveat: I am not an expert in Python development.

No comments: