Checking whether a variable is an integer or not
Confirm if a variable is an integer with Python's isinstance()
function:
Clear-cut and effective, it differentiates integers (int
) from other types such as float
or str
.
For a numeric entity that's covertly integral expressed as a float
, you can verify using:
Going beyond basics
Polymorphism: Python's wildcard
Polymorphism allows Python to treat any object that has integer-like behaviour as an integer.
Safety net: try-except
You can safely execute code and handle any unexpected bare-thumb types using a try-except
clause:
Dealing with antiquities: Python 2.x
In the Python 2.x world, long
type was considered an integer:
Code in disguise: Subclassing and abstract base
int
can be extended or abstract base classes can be used (numbers.Integral
) for creating new numeric types:
An exception with integer's badge: operator.index
operator.index
method allows you to inspect whether an object can be fed to an integer:
Refining the Integer Check
Avoid type checks: Design matters!
Strategical code design can ward off superfluous type checks:
Complex number types— The gray area
Beware that complex numbers with a zero imaginary part remain integers but don't get along well with int(x) == x
.
Language-specific checks
Working with other implementations of Python like Jython or IronPython, ensure that your method for integer checks understands the language nuances.
The simplicity manifesto
Opt for bijective maps and shun obfuscated type checks that may confuse others.
Was this article helpful?