Hacker
Hacker

Reputation: 357

Check if a value is any number in Python

I want to ask if there is a method to check if a value is any number? Is there maybe a "master class" for numbers. I do not want to check every case (int, float, complex). If there is not it is no problem.

In my specific code I now just check every case and than also if it is NaN but that is really annoying.

I have a similar question to data structures: Is there a method that returns whether a value is any of list, tuple, dict or set? Right now I am also checking them every time. So basically my code looks like this:

try:
  value
    if value==None:         #none
      raise Exception("Your value is none")
    elif isinstance(value,str):
      if not value.isnumeric():   #real String
         return value
      else:               #number String
        return (float(value))
    elif isinstance(value,float):
       if math.isnan(value): #nan
         raise Exception("Your number is NaN")
       elif abs(value)>abs(int(value)): #real float
         pass #to-do deal with "real" floats 
       else: #integer
         return int(value)
    elif isinstance(value,int):     #int
      if math.isnan(value): #nan
        raise Exception("Your number is NaN")
      else:
        return value
    elif isinstance(value,tuple):
      pass #to-do recursion
    elif isinstance(value,list):
      pass #to-do recursion
    elif isinstance(value,dict):
      pass #to-do recursion
    elif isinstance(value,set):
      return ("This tool does not support sets yet")
    except NameError: #undefined
        raise Exception("Your value is undefined")

But I feel like it could be much better if there was a method isnumeric() for all values not just strings, like in php.

Regarding my research, I could only find the String isnumeric() method or obviously the type() and isinstance() method.

Please help me but do not tell me there is no better solution.

Upvotes: 2

Views: 6118

Answers (3)

shortorian
shortorian

Reputation: 1182

If you're willing to do add an import, this works:

import numbers

variable = 5
print(isinstance(variable, numbers.Number))

For the second question, do

x = {}
print(type(x) in [list, dict, tuple, set])

Upvotes: 6

Random Davis
Random Davis

Reputation: 6857

Via https://stackabuse.com/python-check-if-variable-is-a-number/:

import numbers

variable = 5
print(isinstance(5, numbers.Number))

Upvotes: 2

Daniel Hao
Daniel Hao

Reputation: 4970

would you like to try this: (from S/O earlier posts What is the most pythonic way to check if an object is a number?)

>>> from numbers import Number
>>> from decimal import Decimal
>>> from fractions import Fraction
>>> for n in [2, 2.0, Decimal('2.0'), complex(2, 0), Fraction(2, 1), '2']:
    print(f'{n!r:>14} {isinstance(n, Number)}')

    
             2 True
           2.0 True
Decimal('2.0') True
        (2+0j) True
Fraction(2, 1) True
           '2' False

Upvotes: 1

Related Questions