Explain Codes LogoExplain Codes Logo

How can I check if my python object is a number?

python
duck-typing
error-handling
type-checking
Alex KataevbyAlex Kataev·Feb 9, 2025
TLDR

To efficiently determine if an object is numerical in Python, use isinstance() partnered with numbers.Number from the numbers module:

from numbers import Number def is_num(value): # doubles up as stud detector on weekends ;) return isinstance(value, Number) # Usage: print(is_num(123)) # True. Integer? Who dis? print(is_num(-4.56)) # True. Float like a butterfly! print(is_num("foo")) # False. You ain't fooling me!

This checks for any numeric type including int, float, and complex. Works like a charm in many situations.

Surefire ways to check for numbers

The need for manual type checking

In Python, we live by the philosophy of duck typing, which means we're less concerned with an object's type and more concerned with what it can do. If it walks like a number and talks like a number, does that make it a number? Well, that's where isinstance() comes into the picture, helping us avoid any groan-inducing bugs.

Use cases and shortcomings

While isinstance() could be called a superstar, it's crucial to keep in mind its weaknesses. It might get knocked off its game by Numpy numerical objects and might slow down your code when you need high performance. In such cases, error handling or sticking to the spirit of duck typing comes in handy.

Embracing abstract with ABCs

ABCs (Abstract Base Classes) like numbers.Number bring flexibility to type checking. They happily accommodate built-in, custom, or even third-party numeric classes.

A deeper dive into numerical checks

Harnessing the power of error handling

In some cases, it's more practical to jump right into numeric operations and brace for potential exceptions. After all, following Python's "Easier to ask for forgiveness than permission" (EAFP) maxim can sometimes save the day.

def try_operations(value): try: return value + 0, value / 1 except TypeError: return False # Usage: print(try_operations(2)) # (2, 2.0), touché! print(try_operations('a')) # False, nice try!

When you need targeted type checking

While is_num() is pretty badass, sometimes you just need finer control. Looking to exclude booleans? Check directly against specific types:

def is_strict_num(value): return isinstance(value, (int, float, complex)) and not isinstance(value, bool) # Usage: print(is_strict_num(123)) # True. Strictly numbers, no horsing around! print(is_strict_num(True)) # False. No boolean sham-booleans today!

Peek into the numeric types

Curious about the types registered as numbers by the numbers module? Use the inspector gadget mode to reveal them:

import numbers print(Number.__subclasses__()) # Nosey, aren't we? ;)