Python
number checking
object type
programming
code validation

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Checking whether an object is numeric in Python depends on context. Sometimes you want to accept all numeric types, sometimes only real numbers, and sometimes you must exclude bool even though it is a subclass of int.

This article shows reliable numeric checks for application code, data pipelines, and API validation.

Core Sections

1) Use numbers.Number for broad numeric acceptance

python
1import numbers
2
3
4def is_number(x):
5    return isinstance(x, numbers.Number)
6
7print(is_number(10))      # True
8print(is_number(3.14))    # True
9print(is_number(2+3j))    # True
10print(is_number("10"))    # False

2) Excluding booleans

python
1import numbers
2
3
4def is_non_bool_number(x):
5    return isinstance(x, numbers.Number) and not isinstance(x, bool)
6
7print(is_non_bool_number(True))  # False

This pattern is common in input validation.

3) Restrict to real values

python
1import numbers
2
3
4def is_real(x):
5    return isinstance(x, numbers.Real) and not isinstance(x, bool)

Use this when complex numbers are not valid in your domain.

4) Parsing numeric strings safely

python
1def parse_float(s):
2    try:
3        return float(s)
4    except (TypeError, ValueError):
5        return None

Type checks and parsing are different concerns; keep them separate.

5) NumPy scalar considerations

python
1import numpy as np
2import numbers
3
4print(isinstance(np.int64(5), numbers.Number))   # True
5print(isinstance(np.array([1,2]), numbers.Number))  # False

Arrays are containers, not scalar numbers.

6) Production checklist for Python numeric validation

Code examples are necessary, but production readiness depends on how this pattern behaves under failure, load, and operational drift. Before rollout, define success criteria that are measurable. A useful baseline is three metrics: correctness (for example, expected output match rate), reliability (error rate and retry behavior), and latency (p95 or p99 execution time). Capture these metrics in a repeatable test environment rather than relying on ad hoc local runs. If external systems are involved, include at least one synthetic fault scenario such as timeout, malformed payload, or temporary dependency outage. This confirms the implementation fails predictably and recovers in a controlled way.

Document environment assumptions close to the code. Include runtime version constraints, required environment variables, and exact dependency versions used during validation. Many regressions come from mismatched environments rather than algorithmic changes. A short README snippet or inline comment that names these assumptions can prevent repeated troubleshooting later. Also define ownership for operational issues: who receives alerts, what threshold triggers action, and what rollback path is acceptable. Without explicit ownership and rollback criteria, otherwise small incidents can take longer to resolve.

A practical rollout sequence is:

  1. Run automated checks (lint, unit tests, static validation) in CI.
  2. Execute a smoke test against representative input sizes.
  3. Validate one failure mode and verify error visibility in logs.
  4. Deploy behind a feature flag or phased rollout if possible.
  5. Monitor key metrics for a defined stabilization window.
bash
1# Example operator workflow
2make lint
3make test
4./scripts/smoke_check.sh

Finally, keep a short limitations section. State what the current approach intentionally does not optimize or support. This prevents accidental misuse by future contributors and keeps design discussions grounded in explicit tradeoffs. For long-lived systems, schedule periodic review of this implementation, especially after runtime upgrades or library changes. A lightweight maintenance cadence often catches compatibility issues before they become production incidents.

Common Pitfalls

  • Treating bool as ordinary numeric input unintentionally.
  • Using type(x) is int and missing numeric subclasses.
  • Mixing parsing logic with type checking in one utility.
  • Accepting complex numbers where only real values are valid.
  • Assuming NumPy arrays behave like scalar numbers.

Summary

Use isinstance with the numbers hierarchy for robust numeric checks, and explicitly define whether booleans and complex values are allowed. Keep parsing and type validation distinct. This yields clear and predictable numeric validation behavior.

A short maintenance note should accompany this implementation in your repository docs so future contributors know expected behavior, validation steps, and rollback options. That small documentation investment usually prevents repeat regressions during dependency upgrades, framework changes, and environment migrations.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.