Simply here is the ultimate code...
def is_int(x: int | float | str | None):
try:
return float(x).is_integer()
except (TypeError, ValueError):
return False
TypeErrorif we try tofloat(None).
ValueErrorif x is a string and contain non-digit characters.
Example usage (test cases)
a1 = 12.0 # True
a2 = "12.0" # True
a3 = "012.0" # True
b1 = 12 # True
b2 = "12" # True
b3 = "012" # True
c1 = 12.34 # False
c2 = "12.34" # False
c3 = "012.34" # False
d1 = None # False
d2 = "12X100ML" # False
d3 = "12.x" # False
print(is_int(a1))
print(is_int(a2))
print(is_int(a3))
print(is_int(b1))
print(is_int(b2))
print(is_int(b3))
print(is_int(c1))
print(is_int(c2))
print(is_int(c3))
print(is_int(d1))
print(is_int(d2))
print(is_int(d3))
Explanation (how it started)
A simple isinstance(x, int) won't work fully enough. It fails when cases like this:
- Number stored as
str. - Integer but represented as
floattype (ex.x=12.0technically it's an integer value right.). - Or some edge cases where string like "abc" or "12.x" should gracefully return
Falserather than crashing.
This is important when we work for web forms, APIs, type strict column on database like on Django (for ex.
models.PositiveIntegerField, etc.).
Here is how my initial code was before getting simplified in the code above.
def is_int(x: int | float | str | None):
if isinstance(x, str):
try:
x = float(x)
except (TypeError, ValueError):
return False
if isinstance(x, int):
return True
if isinstance(x, float):
return x.is_integer()
return False
Yes, you can use regex, but I think it's more complex and why not use the built-in.
For regex version, check on my other post.
Top comments (0)