I wish to cast a string or a number to an integer only if the casting is "lossless" or, another way to put it, only if the string or number is indeed an integer.
For instance,
3.0(a float that is indeed an integer) ->3.'3.000'(a string that is an integer) ->3.3.1-> exception raised.'4.2'-> exception raised.
Directly doing int(x) will convert 3.1 to 3.
This is the best I have:
def safe_cast_to_int(x):
int_x = int(x)
if np.issubdtype(type(x), np.floating):
assert int_x == x, \
f"Can't safely cast a non-integer value ({x}) to integer"
return int_x
but I wonder if there is a better or more Pythonic way?