Explain Codes LogoExplain Codes Logo

Checking whether a variable is an integer or not

python
type-checking
polymorphism
try-except
Nikita BarsukovbyNikita Barsukov·Oct 11, 2024
TLDR

Confirm if a variable is an integer with Python's isinstance() function:

is_integer = isinstance(42, int) # Returns True for integers "by nature"

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:

is_integer = variable.is_integer() if isinstance(variable, float) else isinstance(variable, int)

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:

try: # checking if variable can slip into integer's skin with no changes is_integer = int(variable) == variable except (TypeError, ValueError): is_integer = False # it was a trap, deny everything

Dealing with antiquities: Python 2.x

In the Python 2.x world, long type was considered an integer:

is_integer = isinstance(variable, (int, long)) # embracing both old and new folks

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:

from numbers import Integral class MyInt(int): # be anything, even an integer! pass is_integer = isinstance(MyInt(5), Integral) # Yes, MyInt instances can "int"eract

An exception with integer's badge: operator.index

operator.index method allows you to inspect whether an object can be fed to an integer:

import operator try: index = operator.index(variable) is_integer = True # success! we have a convert except TypeError: is_integer = False # no luck, move on

Refining the Integer Check

Avoid type checks: Design matters!

Strategical code design can ward off superfluous type checks:

def process_number(num: int): # Designing code like this implies num should be an integer. # Violators may be subjected to righteous fury of error messages. pass

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.